Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.help > #2727 > unrolled thread
| Started by | moonhkt <moonhkt@gmail.com> |
|---|---|
| First post | 2013-06-26 22:30 -0700 |
| Last post | 2013-07-01 14:16 -0700 |
| Articles | 7 — 5 participants |
Back to article view | Back to comp.lang.java.help
using TreeMap how to return the Object ? moonhkt <moonhkt@gmail.com> - 2013-06-26 22:30 -0700
Re: using TreeMap how to return the Object ? Jeff Higgins <jeff@invalid.invalid> - 2013-06-27 11:19 -0400
Re: using TreeMap how to return the Object ? Jeff Higgins <jeff@invalid.invalid> - 2013-06-27 13:15 -0400
Re: using TreeMap how to return the Object ? Jeff Higgins <jeff@invalid.invalid> - 2013-07-01 10:49 -0400
Re: using TreeMap how to return the Object ? Lew <lewbloch@gmail.com> - 2013-06-28 10:42 -0700
Re: using TreeMap how to return the Object ? Patricia Shanahan <pats@acm.org> - 2013-06-28 19:13 -0700
Re: using TreeMap how to return the Object ? Gene Wirchenko <genew@telus.net> - 2013-07-01 14:16 -0700
| From | moonhkt <moonhkt@gmail.com> |
|---|---|
| Date | 2013-06-26 22:30 -0700 |
| Subject | using TreeMap how to return the Object ? |
| Message-ID | <f11f9858-f870-42af-a3a3-e9fdb945ba41@googlegroups.com> |
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");
}
}
[toc] | [next] | [standalone]
| From | Jeff Higgins <jeff@invalid.invalid> |
|---|---|
| Date | 2013-06-27 11:19 -0400 |
| Message-ID | <kqhkq6$k8g$1@dont-email.me> |
| In reply to | #2727 |
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");
> }
>
> }
>
[toc] | [prev] | [next] | [standalone]
| From | Jeff Higgins <jeff@invalid.invalid> |
|---|---|
| Date | 2013-06-27 13:15 -0400 |
| Message-ID | <kqhrjo$u2d$1@dont-email.me> |
| In reply to | #2728 |
On 06/27/2013 11:19 AM, Jeff Higgins wrote:
> On 06/27/2013 01:30 AM, moonhkt wrote:
>> 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;
}
}
[toc] | [prev] | [next] | [standalone]
| From | Jeff Higgins <jeff@invalid.invalid> |
|---|---|
| Date | 2013-07-01 10:49 -0400 |
| Message-ID | <kqs4gn$s8l$1@dont-email.me> |
| In reply to | #2728 |
On 06/27/2013 11:19 AM, Jeff Higgins wrote:
> On 06/27/2013 01:30 AM, moonhkt wrote:
>> 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);
>> }
>> }
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);
}
}
}
[toc] | [prev] | [next] | [standalone]
| From | Lew <lewbloch@gmail.com> |
|---|---|
| Date | 2013-06-28 10:42 -0700 |
| Message-ID | <b0645c6d-9955-466b-abb5-5a7c8a3cbc2d@googlegroups.com> |
| In reply to | #2727 |
moonhkt wrote:
> How to using searchKey return object eleHost values?
Since Jeff addressed your primary question, I'll add secondary points.
> cat eleHost.java
Follow the Java naming conventions!
Types begin with an upper-case letter.
> public class eleHost {
>
> String ip;
Why not 'private'?
Why not 'final'?
> String host1;
Where are your Javadoc comments?
> 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.
> cat clsHosts.java
>
> import java.io.*;
Eschew import-on-demand.
Use single-type imports.
> 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.
> // Instance Variables
Don't use pointless comments.
> // 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.
> String ifn = "/etc/hosts" ;
You might want to make this a 'static final String' (compile-time constant variable).
> // Constructor
Another pointless comment. Use Javadoc comments!
Why did you even declare this constructor?
> public clsHosts () {
> }
>
> // Methods
Pointless comment.
> public void process_hosts () {
Follow the Java naming conventions. Use camel case for most identifiers, no underscores.
> File ihost = new File(ifn);
> String delimscfg = "\\s+"; /** multi-space */
Use camel case!
> 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.
> /* System.out.print("-->");
Don't use 'System.out' for debugging or logging.
> 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.
> continue;
> }
> }
> } catch (IOException e) {
> System.out.println(e);
Handle exceptions, don't drop them.
'System.out' is not an 'err' stream.
> }
> }
>
> /* Print all data */
That should be a Javadoc comment!
Make sure your Javadoc comments *exist* and are *complete*.
> public void printAll () {
> Set set = ipx.entrySet();
> Iterator i = set.iterator();
Don't use an explicit iterator.
Don't use single-letter variable names.
> while(i.hasNext()) {
Just use a for loop. A for-each loop will work.
> Map.Entry me = (Map.Entry) i.next();
DO NOT USE RAW TYPES!
That cast were utterly unnecessary had you not done so.
> 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.
> Iterator i = set.iterator ();
It is unusual and probably undesirable to insert a space between method name and parentheses.
> 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.
> public void searchKey (String ip) {
What if 'ip' is 'null'?
> System.out.println( ipx.get(ip));
If you have this, why the loop method?
> }
> }
>
> cat getip.java
>
> class getip {
Naming conventions.
Why not 'public'?
> 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
[toc] | [prev] | [next] | [standalone]
| From | Patricia Shanahan <pats@acm.org> |
|---|---|
| Date | 2013-06-28 19:13 -0700 |
| Message-ID | <e6-dnUVkhedK31PMnZ2dnUVZ_sSdnZ2d@earthlink.com> |
| In reply to | #2730 |
On 6/28/2013 10:42 AM, Lew wrote: ... >> // 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
[toc] | [prev] | [next] | [standalone]
| From | Gene Wirchenko <genew@telus.net> |
|---|---|
| Date | 2013-07-01 14:16 -0700 |
| Message-ID | <cas3t8tqacs6qo17u9ge8sla74h3bk5u0e@4ax.com> |
| In reply to | #2731 |
On Fri, 28 Jun 2013 19:13:47 -0700, Patricia Shanahan <pats@acm.org>
wrote:
>On 6/28/2013 10:42 AM, Lew wrote:
>...
>>> // 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
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.java.help
csiph-web