How treeMap works?

Discussion in 'Java' started by Sanny, Feb 25, 2008.

  1. Sanny

    Sanny Guest

    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
    Sanny, Feb 25, 2008
    #1
    1. Advertising

  2. In article
    <>,
    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.
    >
    > 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
    Steve W. Jackson, Feb 25, 2008
    #2
    1. Advertising

  3. Sanny

    Jeff Higgins Guest

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


    }
    Jeff Higgins, Feb 25, 2008
    #3
  4. Sanny

    Roedy Green Guest

    On Mon, 25 Feb 2008 08:27:32 -0800 (PST), Sanny
    <> 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
    Roedy Green, Feb 25, 2008
    #4
  5. Sanny

    Sanny Guest

    > 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
    Sanny, Feb 26, 2008
    #5
  6. 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.
    RedGrittyBrick, Feb 26, 2008
    #6
  7. 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-----
    Hendrik Maryns, Feb 26, 2008
    #7
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ahmed Moustafa

    HashMap vs TreeMap

    Ahmed Moustafa, Aug 9, 2003, in forum: Java
    Replies:
    2
    Views:
    46,406
    Roedy Green
    Aug 10, 2003
  2. Harry

    TreeMap problem...

    Harry, Sep 22, 2003, in forum: Java
    Replies:
    3
    Views:
    468
    Harry
    Sep 23, 2003
  3. Wendy S
    Replies:
    4
    Views:
    14,225
    Jim McMaster
    Feb 19, 2004
  4. Miguel Angel
    Replies:
    9
    Views:
    13,795
    Christian Kaufhold
    Apr 15, 2004
  5. news.amnet.net.au

    Empty values in TreeMap - cannnot be removed?

    news.amnet.net.au, Apr 19, 2004, in forum: Java
    Replies:
    3
    Views:
    914
    Roedy Green
    Apr 19, 2004
Loading...

Share This Page