How treeMap works?

  • Follow


I was going through TreeMaps and HashMaps Looks like they are samething.Basically I want them to sort a data and then resort them when a valueis changed.I learnt to put a data in treeMap/ HashMap we use.Treemap.put(key,data)LikeHaspmap map1;map1..put(5,"Ferrari");map1..put(9,"Toyota");map1..put(2,"Ford");Now to sort them based on key I use TreeMapTreemap 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. Howwill I change the Value and resort the HaspMap?Please Advice.ByeSanny
0
Reply softtanks (48) 2/25/2008 4:27:32 PM

In article <1da0f9eb-28f7-47a6-bb57-d568619536e5@s12g2000prg.googlegroups.com>, Sanny <softtanks@hotmail.com> 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> SannyHashMap 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. JacksonMontgomery, Alabama
0
Reply Steve 2/25/2008 4:48:34 PM


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;    }  }}
0
Reply Jeff 2/25/2008 8:52:04 PM

On Mon, 25 Feb 2008 08:27:32 -0800 (PST), Sanny<softtanks@hotmail.com> wrote, quoted or indirectly quoted someone whosaid :>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 allthe time as you add elements.HashMaps are when you don't care about order, just lookup, or whenextracting the data and sorting an array from time to time willsuffice.--Roedy Green Canadian Mind ProductsThe Java Glossaryhttp://mindprod.com
0
Reply Roedy 2/25/2008 8:59:57 PM

> 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 TreeMapafter 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 thenagain add it.If the TreeMap is Sorted, And I add a new element Will it be alwaysadded in a place so that it is always Sorted?Is it very fast to add & delete values in a TreeMap?ByeSanny
0
Reply Sanny 2/26/2008 7:03:42 AM

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/api/java/util/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.
0
Reply RedGrittyBrick 2/26/2008 9:56:58 AM

This is an OpenPGP/MIME signed message (RFC 2440 and 3156)
--------------enig18903F26C45B501025A490A7
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: quoted-printable

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.
>=20
> oldValue =3D treeMap.get(key);
> treeMap.remove(key);
> treeMap.put(newkey, oldValue);

 From what the OP is telling us, it seems like he needs a TreeSet=20
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 =3D type;
     this.valuation =3D 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 =3D new TreeSet<Car>();
     Car mercedes =3D new Car("Mercedes E-Klasse", 9);
     Car smart =3D new Car("Smart ForTwo", 10);
     Car lamborghini =3D new Car("Lamborghini", 1);
     Car bycicle =3D new Car("save the planet: take your bycicle",=20
Integer.MAX_VALUE);
     Collections.addAll(myCars, mercedes, smart, lamborghini, bycicle);
     System.out.println(myCars);
// prints [save the planet: take your bycicle, Smart ForTwo, Mercedes=20
E-Klasse, Lamborghini]
     // now Mercedes enhances their E-type to use less gas, we want to=20
re-evaluate it
    myCars.remove(mercedes);
    mercedes.valuation =3D 11;
    myCars.add(mercedes);
     System.out.println(myCars);
// prints [save the planet: take your bycicle, Mercedes E-Klasse, Smart=20
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=20
the time.  It only computes it at insertion.

Untested, uncompiled.

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


--------------enig18903F26C45B501025A490A7
Content-Type: application/pgp-signature; name="signature.asc"
Content-Description: OpenPGP digital signature
Content-Disposition: attachment; filename="signature.asc"

-----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-----

--------------enig18903F26C45B501025A490A7--
0
Reply Hendrik 2/26/2008 4:04:22 PM

6 Replies
214 Views

(page loaded in 0.124 seconds)

Similiar Articles:





7/22/2012 2:13:11 PM


Reply: