Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > How treeMap works?

Reply
Thread Tools

How treeMap works?

 
 
Sanny
Guest
Posts: n/a
 
      02-25-2008
I was going through TreeMaps and HashMaps Looks like they are same
thing.

Basically I want them to sort a data and then resort them when a value
is changed.

I learnt to put a data in treeMap/ HashMap we use.

Treemap.put(key,data)

Like

Haspmap map1;

map1..put(5,"Ferrari");
map1..put(9,"Toyota");
map1..put(2,"Ford");

Now to sort them based on key I use TreeMap

Treemap tree1 = new Treemap(map1);

So now the TreeMap is Sorted.

But Now I want to Change the Value for Toyota from 9 to say 12. How
will I change the Value and resort the HaspMap?

Please Advice.

Bye
Sanny



 
Reply With Quote
 
 
 
 
Steve W. Jackson
Guest
Posts: n/a
 
      02-25-2008
In article
<(E-Mail Removed)>,
Sanny <(E-Mail Removed)> wrote:

> I was going through TreeMaps and HashMaps Looks like they are same
> thing.
>
> Basically I want them to sort a data and then resort them when a value
> is changed.
>
> I learnt to put a data in treeMap/ HashMap we use.
>
> Treemap.put(key,data)
>
> Like
>
> Haspmap map1;
>
> map1..put(5,"Ferrari");
> map1..put(9,"Toyota");
> map1..put(2,"Ford");
>
> Now to sort them based on key I use TreeMap
>
> Treemap tree1 = new Treemap(map1);
>
> So now the TreeMap is Sorted.
>
> But Now I want to Change the Value for Toyota from 9 to say 12. How
> will I change the Value and resort the HaspMap?
>
> Please Advice.
>
> Bye
> Sanny


HashMap and TreeMap are *not* the same thing. You should read the API
descriptions for each, where you'll find that HashMap implements the Map
interface while TreeMap implements both the Map and SortedMap interfaces.

And then you'll also note that TreeMap always keeps itself sorted by the
*key* and not the value (which you refer to above as data). In your
example, the HashMap named map1 gets put into the TreeMap, which will
then be sorted according to the natural order of its numeric keys.
Assuming Java 5 or 6, those values are autoboxed into Integer objects,
since you cannot use a primitive int for the key.

You cannot change the value for Toyota because Toyota is the value, not
the key. If your intent is to have a map of some kind where those model
names are key, then have a second map sorted by the numeric values,
you'll want to take a different approach.
--
Steve W. Jackson
Montgomery, Alabama
 
Reply With Quote
 
 
 
 
Jeff Higgins
Guest
Posts: n/a
 
      02-25-2008

Sanny wrote
>I was going through TreeMaps and HashMaps Looks like they are same
> thing.
>
> Basically I want them to sort a data and then resort them when a value
> is changed.
>


import java.util.Comparator;


public class CarComparisons {

public static void main(String[] args) {

Car car1 = new Car();
//What is the value of car1?

boolean comparison1 = (car1 == null);
//What is the value of comparison1?
boolean comparison2 = (car1 == car1);
//What is the value of comparison2?
boolean comparison3 = (car1.equals(null));
//What is the value of comparison3?
boolean comparison4 = (car1.equals(car1));
//What is the value of comparison4?




IntegerCar car2 =
new IntegerCar(Integer.valueOf(1));
//What is the value of car2?
car2.setNumber(Integer.valueOf(2));
//What is the value of car3?
IntegerCar car3 =
new IntegerCar(Integer.valueOf(2));
// What is the value of car3

boolean comparison5 = car2.equals(car3);
//What is the value of comparison4?
int comparison6 =
car2.getNumber().compareTo(car3.getNumber());
// What is the value of comparison6?



IntegerValueComparableCar car5 =
new IntegerValueComparableCar(Integer.valueOf(1));
IntegerValueComparableCar car6 =
new IntegerValueComparableCar(Integer.valueOf(2));
int comparison9 = (car5.compareTo(car6));
// What is the value of comparison9?
car5.setNumber(Integer.valueOf(2));
int comparison10 = (car5.compareTo(car6));
// What is the value of comparison10?


TwoValueCar car7 =
new TwoValueCar(Integer.valueOf(1), "chevrolet");
TwoValueCar car8 =
new TwoValueCar(Integer.valueOf(2), "ford");

NumberComparator numberComparator =
new NumberComparator();
NameComparator nameComparator =
new NameComparator();
NumberNameComparator numberNameComparator =
new NumberNameComparator(false);

TwoValueCar[] carArray = {car7, car8};

// now it's play time
// make some Sets, Lists, Maps
// add, remove, iterate, compare, find, etc...

}

public static class Car
extends Object {

}

public static class IntegerCar
extends Car {

private Integer number;

public IntegerCar(Integer number) {
this.number = number;
}

public Integer getNumber() {
return number;
}

public void setNumber(Integer number) {
this.number = number;
}

}

public static class IntegerValueComparableCar
extends IntegerCar
implements Comparable<IntegerCar> {

public IntegerValueComparableCar(Integer number) {
super(number);
}

@Override
public int compareTo(IntegerCar that) {
return super.number.compareTo(that.number);
}

}

public static class TwoValueCar
extends IntegerCar {

String name;

public TwoValueCar(Integer number) {
super(number);
this.name = "chevrolet";
}

public TwoValueCar(Integer number, String name) {
super(number);
this.name = name;
}

public Integer getNumber() {
return super.number;
}

public String getName() {
return name;
}

public void setNumber(Integer number) {
super.number = number;
}

public void setName(String name) {
this.name = name;
}

}

public static class NumberComparator
implements Comparator<TwoValueCar> {

@Override
public int compare(TwoValueCar car0, TwoValueCar car1) {
return car0.getNumber().compareTo(car1.getNumber());
}

}

public static class NameComparator
implements Comparator<TwoValueCar> {

@Override
public int compare(TwoValueCar car0, TwoValueCar car1) {
return car0.getName().compareTo(car1.getName());
}

}

public static class NumberNameComparator
implements Comparator<TwoValueCar> {

private final boolean compareByNumber;

public NumberNameComparator(boolean compareByNumber) {
this.compareByNumber = compareByNumber;
}

@Override
public int compare(TwoValueCar car0, TwoValueCar car1) {
if (compareByNumber) {
return car0.getNumber().compareTo(car1.getNumber());
}
else {
return car0.name.compareToIgnoreCase(car1.name);
}

}

}

public static class CarDriver {
public final String height;
public CarDriver(String height) {
this.height = height;
}
}


}


 
Reply With Quote
 
Roedy Green
Guest
Posts: n/a
 
      02-25-2008
On Mon, 25 Feb 2008 08:27:32 -0800 (PST), Sanny
<(E-Mail Removed)> wrote, quoted or indirectly quoted someone who
said :

>But Now I want to Change the Value for Toyota from 9 to say 12. How
>will I change the Value and resort the HaspMap?


TreeMaps are when you want the data to automatically stay sorted all
the time as you add elements.

HashMaps are when you don't care about order, just lookup, or when
extracting the data and sorting an array from time to time will
suffice.
--

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
 
Reply With Quote
 
Sanny
Guest
Posts: n/a
 
      02-26-2008
> TreeMaps are when you want the data to automatically stay sorted all
> the time as you add elements.
>
> HashMaps are when you don't care about order, just lookup, or when
> extracting the data and sorting an array from time to time will
> suffice.


Steve W. Jackson above said you cannot Change the data in a TreeMap
after we have inserted it, So it is of no use for me.

I want to change key values and again resort them.

Id there any way to delete a particular Key and modify it and then
again add it.

If the TreeMap is Sorted, And I add a new element Will it be always
added in a place so that it is always Sorted?

Is it very fast to add & delete values in a TreeMap?

Bye
Sanny



 
Reply With Quote
 
RedGrittyBrick
Guest
Posts: n/a
 
      02-26-2008
Sanny wrote:
>> TreeMaps are when you want the data to automatically stay sorted all
>> the time as you add elements.
>>
>> HashMaps are when you don't care about order, just lookup, or when
>> extracting the data and sorting an array from time to time will
>> suffice.

>
> Steve W. Jackson above said you cannot Change the data in a TreeMap
> after we have inserted it, So it is of no use for me.
>
> I want to change key values and again resort them.
>
> Id there any way to delete a particular Key and modify it and then
> again add it.


oldValue = treeMap.get(key);
treeMap.remove(key);
treeMap.put(newkey, oldValue);

>
> If the TreeMap is Sorted, And I add a new element Will it be always
> added in a place so that it is always Sorted?


http://java.sun.com/j2se/1.5.0/docs/...l/TreeMap.html
"This class guarantees that the map will be in ascending key order"

I'm rather puzzled why you are unable to read the Javadocs and need to
have strangers read it for you.

If I doubted the Javadocs, before posting here I'd spend a few minutes
writing a test program that did something like:

treeMap.put(1,"one");
treeMap.put(3,"three");
treeMap.put(2,"two");
for (String value: treeMap.values())
System.out.println(value);

>
> Is it very fast to add & delete values in a TreeMap?
>


The main rule of optimising is "don't". What you should do is wait until
you need to optimise, only then spend time optimising.
 
Reply With Quote
 
Hendrik Maryns
Guest
Posts: n/a
 
      02-26-2008
RedGrittyBrick schreef:
> Sanny wrote:
>>> TreeMaps are when you want the data to automatically stay sorted all
>>> the time as you add elements.
>>>
>>> HashMaps are when you don't care about order, just lookup, or when
>>> extracting the data and sorting an array from time to time will
>>> suffice.

>>
>> Steve W. Jackson above said you cannot Change the data in a TreeMap
>> after we have inserted it, So it is of no use for me.
>>
>> I want to change key values and again resort them.
>>
>> Id there any way to delete a particular Key and modify it and then
>> again add it.

>
> oldValue = treeMap.get(key);
> treeMap.remove(key);
> treeMap.put(newkey, oldValue);


From what the OP is telling us, it seems like he needs a TreeSet
though. Code would be similar; say you want to change the :

class Car implements Comparable<Car> {
/**
* How much I appreciate this car.
*/
int valuation;
/**
* The make.
*/
String type; // this rather asks for subclassing

/**
* A new care with the given type and appreciation.
*/
public Car(String type, int valuation) {
this.type = type;
this.valuation = valuation;
}

// methods for Car

/**
* Cars are compared by their appreciation value.
*/
public int compareTo(Car otherCar) {
return Integer.compare(this.valuation, otherCar.valuation);
}
/**
* The type determines the car.
*/
@Override
public int toString(Car otherCar) {
return type;
}

}

class TestCars {
public static void main(String[] args) {
TreeSet<Car> myCars = new TreeSet<Car>();
Car mercedes = new Car("Mercedes E-Klasse", 9);
Car smart = new Car("Smart ForTwo", 10);
Car lamborghini = new Car("Lamborghini", 1);
Car bycicle = new Car("save the planet: take your bycicle",
Integer.MAX_VALUE);
Collections.addAll(myCars, mercedes, smart, lamborghini, bycicle);
System.out.println(myCars);
// prints [save the planet: take your bycicle, Smart ForTwo, Mercedes
E-Klasse, Lamborghini]
// now Mercedes enhances their E-type to use less gas, we want to
re-evaluate it
myCars.remove(mercedes);
mercedes.valuation = 11;
myCars.add(mercedes);
System.out.println(myCars);
// prints [save the planet: take your bycicle, Mercedes E-Klasse, Smart
ForTwo, Lamborghini]
}
}

Unfortunately, you *have to* remove and re-add the car if you change its
valuation. This is because TreeSet does not recompute the ordering all
the time. It only computes it at insertion.

Untested, uncompiled.

HTH, H.
--
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.4-svn0 (GNU/Linux)
Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org

iD8DBQFHxDiMe+7xMGD3itQRAkGfAJsGgTVSyf5Z/gG2U8hoVRkK3iCneQCggRnC
KFlTp//hng/VWRBnbPrGklU=
=xBD2
-----END PGP SIGNATURE-----

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
(newbie) converting a hashmap to a treemap Miguel Angel Java 9 04-15-2004 01:28 PM
Help with sorting values in a TreeMap Wendy S Java 4 02-19-2004 07:17 AM
TreeMap problem... Harry Java 3 09-23-2003 11:02 AM
HashMap vs TreeMap Ahmed Moustafa Java 2 08-10-2003 03:31 AM



Advertisments