Re: using TreeMap how to return the Object ?
On 06/27/2013 01:30 AM, moonhkt wrote:
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?
cat eleHost.java
You might consider something like java.net.InetAddress.
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?
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.
/* 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.
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");
}
}