Discussion:
using TreeMap how to return the Object ?
(too old to reply)
moonhkt
2013-06-27 05:30:36 UTC
Permalink
Hi All


How to using searchKey return object eleHost values?


cat eleHost.java

public class eleHost {
String ip;
String host1;

public eleHost (String a, String b) {
this.ip = a;
this.host1 = b;
}
/* public String toString () {
return ip + "|" + host1;
} */
}

cat clsHosts.java

import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.lang.String.*;
import java.text.*;

public class clsHosts {
// Instance Variables
// http://kerflyn.wordpress.com/2011/05/20/how-treemap-can-save-your-day/
TreeMap ipx = new TreeMap () ; /* a sorted and navigable map */
String ifn = "/etc/hosts" ;

// Constructor
public clsHosts () {
}
// Methods
public void process_hosts () {
File ihost = new File(ifn);
String delimscfg = "\\s+"; /** multi-space */
String aline ;
int i = 0 ;
try {
BufferedReader br1 = new BufferedReader(new FileReader(ihost));
while ((aline = br1.readLine()) != null) {
String [] tokens = aline.split(delimscfg);
try {
if ( ! tokens[0].trim().startsWith("#")) {
/* System.out.print("-->");
System.out.print(tokens[0].trim());
System.out.print(" ");
System.out.print(tokens[0].trim().substring(0));
System.out.println("<--"); */
ipx.put(tokens[0].trim(),new eleHost(tokens[1].trim(),"x"));
}
} catch (ArrayIndexOutOfBoundsException e) {
continue;
}
}
} catch (IOException e) {
System.out.println(e);
}
}
/* Print all data */
public void printAll () {
Set set = ipx.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.printf("%-18s %-25s\n" , me.getKey() , me.getValue());
}
}
/* get Hostname by IP address */
public String getHost (String ip) {
Set set = ipx.entrySet ();
Iterator i = set.iterator ();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next ();
if (me.getKey().equals(ip)) {
return me.getValue().toString();
}
}
return null;
}
public void searchKey (String ip) {
System.out.println( ipx.get(ip));
}
}

cat getip.java

class getip {

public static void main (String args[]) throws Exception {
clsHosts v = new clsHosts();
String rtn ;
v.process_hosts();
v.printAll();
rtn = v.getHost("21xxxxxxx");
System.out.println("rtn=" + rtn);
v.searchKey("21xxxxxxx");
}

}
Jeff Higgins
2013-06-27 15:19:49 UTC
Permalink
Post by moonhkt
Hi All
How to using searchKey return object eleHost values?
Return from where? Do you mean how to arrange for your
searchKey method to return an eleHost value?
Post by moonhkt
cat eleHost.java
You might consider something like java.net.InetAddress.
Post by moonhkt
public class eleHost {
String ip;
String host1;
public eleHost (String a, String b) {
this.ip = a;
this.host1 = b;
}
/* public String toString () {
return ip + "|" + host1;
} */
}
cat clsHosts.java
import java.io.*;
import java.util.*;
import java.util.regex.*;
import java.lang.String.*;
import java.text.*;
public class clsHosts {
// Instance Variables
// http://kerflyn.wordpress.com/2011/05/20/how-treemap-can-save-your-day/
TreeMap ipx = new TreeMap () ; /* a sorted and navigable map */
String ifn = "/etc/hosts" ;
// Constructor
public clsHosts () {
}
// Methods
public void process_hosts () {
File ihost = new File(ifn);
String delimscfg = "\\s+"; /** multi-space */
String aline ;
int i = 0 ;
try {
BufferedReader br1 = new BufferedReader(new FileReader(ihost));
while ((aline = br1.readLine()) != null) {
String [] tokens = aline.split(delimscfg);
try {
if ( ! tokens[0].trim().startsWith("#")) {
/* System.out.print("-->");
System.out.print(tokens[0].trim());
System.out.print(" ");
System.out.print(tokens[0].trim().substring(0));
System.out.println("<--"); */
You'll want a (probably immutable) java.util.Comparable key,
or a java.util.Comparator for your key in a java.util.SortedMap.

Why store your key with your value?
Post by moonhkt
ipx.put(tokens[0].trim(),new eleHost(tokens[1].trim(),"x"));
}
} catch (ArrayIndexOutOfBoundsException e) {
continue;
}
}
} catch (IOException e) {
System.out.println(e);
}
}
/* Print all data */
public void printAll () {
Set set = ipx.entrySet();
Iterator i = set.iterator();
while(i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
System.out.printf("%-18s %-25s\n" , me.getKey() , me.getValue());
}
}
It looks as if you've defeated the Map concept.
Post by moonhkt
/* get Hostname by IP address */
public String getHost (String ip) {
Set set = ipx.entrySet ();
Iterator i = set.iterator ();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next ();
if (me.getKey().equals(ip)) {
return me.getValue().toString();
}
}
return null;
}
If this method is the subject of your post
just make it return an eleHost instance.
Post by moonhkt
public void searchKey (String ip) {
System.out.println( ipx.get(ip));
}
}
cat getip.java
class getip {
public static void main (String args[]) throws Exception {
clsHosts v = new clsHosts();
String rtn ;
v.process_hosts();
v.printAll();
rtn = v.getHost("21xxxxxxx");
System.out.println("rtn=" + rtn);
v.searchKey("21xxxxxxx");
}
}
Jeff Higgins
2013-06-27 17:15:51 UTC
Permalink
Post by moonhkt
Hi All
public class HostsTest {

private final Hosts hosts;

{ hosts = new Hosts(); }

public static void main(String[] args) {
HostsTest test = new HostsTest();
test.fillHosts("\\etc\\hosts");
}

public boolean fillHosts(String filename) {

/*
* TODO
*/

return false;
}

public Host getHost(IPAddress address) {

/*
* TODO
*/

return null;
}

}

public class IPAddress implements Comparable<IPAddress> {

/*
* IPV4 addresses are 32 bit values
* IPV6 addresses are 128 bit values
* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/

// some private final field to hold your address value.
// some constructor(s)

@Override
public int compareTo(IPAddress address) {
// TODO Auto-generated method stub
return 0;
}

@Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}

@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}

@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString();
}
}

import java.util.ArrayList;
import java.util.List;

public class Host {

private final String hostName;
private final List<String> aliases;

{ aliases = new ArrayList<String>(); }

public Host(String hostname) {
hostName = hostname;
}

/*
* TODO
*/

}

import java.util.Map;
import java.util.TreeMap;


public class Hosts {

private final Map<IPAddress, Host> map;

{ map = new TreeMap<IPAddress, Host>(); }

public Host getHostFromIPAddress(IPAddress address) {

/*
* TODO
*/

return null;
}

}
Jeff Higgins
2013-07-01 14:49:37 UTC
Permalink
Post by Jeff Higgins
Post by moonhkt
public void process_hosts () {
File ihost = new File(ifn);
String delimscfg = "\\s+"; /** multi-space */
String aline ;
int i = 0 ;
try {
BufferedReader br1 = new BufferedReader(new FileReader(ihost));
while ((aline = br1.readLine()) != null) {
String [] tokens = aline.split(delimscfg);
try {
if ( ! tokens[0].trim().startsWith("#")) {
/* System.out.print("-->");
System.out.print(tokens[0].trim());
System.out.print(" ");
System.out.print(tokens[0].trim().substring(0));
System.out.println("<--"); */
You'll want a (probably immutable) java.util.Comparable key,
or a java.util.Comparator for your key in a java.util.SortedMap.
Why store your key with your value?
Post by moonhkt
ipx.put(tokens[0].trim(),new
eleHost(tokens[1].trim(),"x"));
}
} catch (ArrayIndexOutOfBoundsException e) {
continue;
}
}
} catch (IOException e) {
System.out.println(e);
}
}
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Arrays;

import sun.net.util.IPAddressUtil;

/**
* <p>This class represents an Internet Protocol Version 6 (IPv6)
address.</p>
* <p>An instance of an IPv6Address consists of an raw IPv6 address
* (a sixteen element byte array) and has no knowledge of the internal
* (IPv6) structure of the raw IPv6 address.</p>
* <p>This class is intended to demonstrate concepts discussed in a
usenet posting.</p>
* <p><strong>FOR TESTING PURPOSES ONLY -- NOT FOR PRODUCTION
USE</strong></p>
* @author jeff
*
*/
public final class IPv6Address implements Comparable<IPv6Address> {

/**
* <p>Creates an IPv6Address based on the provided IPv6 raw address.</p>
* <p>If address is null, or other than sixteen bytes in length,
* the IPv6 unspecified address is returned.</p>
* <p>Possible to introduce an IPv6 mapped or compatible IPv4 address
here.</p>
*
* @param address a sixteen element byte array (raw IPv6 address)
* @return an IPv6Address object created from the raw IP address,
* or the IPv6 unspecified address if address is null or other than
sixteen bytes in length
*/
public static IPv6Address valueOf(byte[] address) {
return new IPv6Address(address);
}

/**
* <p>Creates an IPv6Address based on the provided IPv6 address
textual representation.</p>
* <p>If address is null, or otherwise invalid,
* the IPv6 unspecified address is returned.</p>
* <p>IPv6 mapped or compatible IPv4 address are considered invalid
here.</p>
*
* @param text representation of an IPv6 address
* @return an IPv6Address object created from the IPv6 address text,
* or the IPv6 unspecified address if address is null or invalid per
* sun.net.util.IPAddressUtil.textToNumericFormatV6(address)
*/
public static IPv6Address valueOf(String address) {
return new IPv6Address(address);
}

/**
* The IPv6 raw address stored by this class is in network byte order,
* the MSB is at index 0 and the LSB is at index 15.</p>
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(IPv6Address address) {
int comparison = 0;
for (int i = 0; i < bytes.length; i++) {
comparison = Byte.compare(bytes[i], address.bytes[i]);
if (comparison != 0)
break;
}
return comparison;
}

/*
* (non-Javadoc)
*
* IDE generated equals method
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IPv6Address other = (IPv6Address) obj;
if (!Arrays.equals(bytes, other.bytes))
return false;
return true;
}

/*
* (non-Javadoc)
*
* IDE generated hashCode method
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(bytes);
return result;
}

/**
* <p>Converts this IP address to a String. The string returned
* is of the IPv6 "preferred" form:</p>
* <p>RFC2373 Section 2.2 Text Representation of Addresses
* <p>1. The preferred form is x:x:x:x:x:x:x:x, where the 'x's are the
* hexadecimal values of the eight 16-bit pieces of the address.
* <br>Examples:</p>
* <pre>
FEDC:BA98:7654:3210:FEDC:BA98:7654:3210

1080:0:0:0:8:800:200C:417A
* </pre>
*
* @return a string representation of this IP address
* @see java.lang.Object#toString()
*/
@Override
public String toString() {

StringBuilder builder = new StringBuilder();
CharBuffer buffer = ByteBuffer.wrap(bytes).asCharBuffer();
while (buffer.hasRemaining()) {
builder.append(Integer.toHexString(buffer.get()));
if (buffer.hasRemaining())
builder.append(":");
}
return builder.toString();
}

private final byte[] bytes;

private IPv6Address(byte[] address) {
bytes = new byte[16];
if (address != null && address.length == 16)
System.arraycopy(address, 0, bytes, 0, 16);
}

private IPv6Address(String address) {
@SuppressWarnings("restriction")
byte[] test = IPAddressUtil.textToNumericFormatV6(address);
bytes = new byte[16];
if (test != null && test.length == 16) {
System.arraycopy(test, 0, bytes, 0, 16);
}
}
}
Lew
2013-06-28 17:42:39 UTC
Permalink
Post by moonhkt
How to using searchKey return object eleHost values?
Since Jeff addressed your primary question, I'll add secondary points.
Post by moonhkt
cat eleHost.java
Follow the Java naming conventions!

Types begin with an upper-case letter.
Post by moonhkt
public class eleHost {
String ip;
Why not 'private'?

Why not 'final'?
Post by moonhkt
String host1;
Where are your Javadoc comments?
Post by moonhkt
public eleHost (String a, String b) {
this.ip = a;
this.host1 = b;
}
/* public String toString () {
return ip + "|" + host1;
} */
}
You need to override 'equals()' and 'hashCode()' in 'eleHost' (and of course, rename the type).

'equals()' and 'hashCode()' must always be consistent, and overridden together or not at all.
'toString()' should use at least the fields used for 'equals()' and 'hashCode()'.
If the type implements 'Comparable', you also need to override 'compareTo()' and make it consistent with 'equals()' and 'hashCode()'.

You need to override these methods if you wish comparisons and ordering in your 'TreeMap()' to work
correctly.

To use 'TreeMap', the base type must either be 'Comparable' or have an associated 'Comparator'
passed to the map.
Post by moonhkt
cat clsHosts.java
import java.io.*;
Eschew import-on-demand.

Use single-type imports.
Post by moonhkt
import java.util.*;
import java.util.regex.*;
import java.lang.String.*;
import java.text.*;
public class clsHosts {
Naming conventions.

Why do you put 'cls' into the name? it contributes nothing.
Post by moonhkt
// Instance Variables
Don't use pointless comments.
Post by moonhkt
// http://kerflyn.wordpress.com/2011/05/20/how-treemap-can-save-your-day/
TreeMap ipx = new TreeMap () ; /* a sorted and navigable map */
DO NOT USE RAW TYPES!

Don't use pointless comments.

Do use better variable names. 'ipx' reveals nothing.
Post by moonhkt
String ifn = "/etc/hosts" ;
You might want to make this a 'static final String' (compile-time constant variable).
Post by moonhkt
// Constructor
Another pointless comment. Use Javadoc comments!

Why did you even declare this constructor?
Post by moonhkt
public clsHosts () {
}
// Methods
Pointless comment.
Post by moonhkt
public void process_hosts () {
Follow the Java naming conventions. Use camel case for most identifiers, no underscores.
Post by moonhkt
File ihost = new File(ifn);
String delimscfg = "\\s+"; /** multi-space */
Use camel case!
Post by moonhkt
String aline ;
int i = 0 ;
try {
BufferedReader br1 = new BufferedReader(new FileReader(ihost));
while ((aline = br1.readLine()) != null) {
String [] tokens = aline.split(delimscfg);
try {
if ( ! tokens[0].trim().startsWith("#")) {
What if 'tokens' has no elements or is 'null'?

It is not an exception, so don't use exception handling for it.
Post by moonhkt
/* System.out.print("-->");
Don't use 'System.out' for debugging or logging.
Post by moonhkt
System.out.print(tokens[0].trim());
System.out.print(" ");
System.out.print(tokens[0].trim().substring(0));
System.out.println("<--"); */
ipx.put(tokens[0].trim(),new eleHost(tokens[1].trim(),"x"));
}
} catch (ArrayIndexOutOfBoundsException e) {
Don't use exceptions for if-then tests. Don't ignore exceptions.
Post by moonhkt
continue;
}
}
} catch (IOException e) {
System.out.println(e);
Handle exceptions, don't drop them.
'System.out' is not an 'err' stream.
Post by moonhkt
}
}
/* Print all data */
That should be a Javadoc comment!

Make sure your Javadoc comments *exist* and are *complete*.
Post by moonhkt
public void printAll () {
Set set = ipx.entrySet();
Iterator i = set.iterator();
Don't use an explicit iterator.

Don't use single-letter variable names.
Post by moonhkt
while(i.hasNext()) {
Just use a for loop. A for-each loop will work.
Post by moonhkt
Map.Entry me = (Map.Entry) i.next();
DO NOT USE RAW TYPES!

That cast were utterly unnecessary had you not done so.
Post by moonhkt
System.out.printf("%-18s %-25s\n" , me.getKey() , me.getValue());
}
}
/* get Hostname by IP address */
public String getHost (String ip) {
Set set = ipx.entrySet ();
Read the ** manual on how to use maps.

Don't use the entry set. Do not use the iterator. Use the freaking 'get' method.

Seriously, you are looping through a map to get the associated value for a key?

Seriously?

Surely you jest.
Post by moonhkt
Iterator i = set.iterator ();
It is unusual and probably undesirable to insert a space between method name and parentheses.
Post by moonhkt
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next ();
if (me.getKey().equals(ip)) {
return me.getValue().toString();
}
}
return null;
}
If you're going to do this anyway, do not use a map.
Post by moonhkt
public void searchKey (String ip) {
What if 'ip' is 'null'?
Post by moonhkt
System.out.println( ipx.get(ip));
If you have this, why the loop method?
Post by moonhkt
}
}
cat getip.java
class getip {
Naming conventions.

Why not 'public'?
Post by moonhkt
public static void main (String args[]) throws Exception {
clsHosts v = new clsHosts();
String rtn ;
v.process_hosts();
v.printAll();
rtn = v.getHost("21xxxxxxx");
System.out.println("rtn=" + rtn);
v.searchKey("21xxxxxxx");
}
}
--
Lew
Patricia Shanahan
2013-06-29 02:13:47 UTC
Permalink
On 6/28/2013 10:42 AM, Lew wrote:
...
Post by Lew
Post by moonhkt
// Instance Variables
Don't use pointless comments.
...

I suspect these comments may be the result of keeping the code organized
by designating where constructors, fields etc. are going to be placed.
Although I agree in general that one should avoid comments that merely
repeat what the code says, that may be a harmless exception.

Patricia
Gene Wirchenko
2013-07-01 21:16:21 UTC
Permalink
Post by Patricia Shanahan
...
Post by Lew
Post by moonhkt
// Instance Variables
Don't use pointless comments.
...
I suspect these comments may be the result of keeping the code organized
by designating where constructors, fields etc. are going to be placed.
Although I agree in general that one should avoid comments that merely
repeat what the code says, that may be a harmless exception.
I agree with you, Patricia, except that I call it a *useful*
exception.

Sincerely,

Gene Wirchenko

Loading...