Collection.addAll?

I have an arbitary object an override the equals() method on the object.
eg.
public class Thing {
public boolean equals() {
I have a Vector of these Thing objects.
Now the problem I get is when I create a HashSet and add the Vector using addAll(Collection c) method, the signature of the collection is added correctly, however when I call the contains(Object o) method, the signature of the equals() method points to the Object.equals() method instead of Thing.equals().
eg.
Vector v = new Vector();
Thing thing1 = new Thing();
thing1.setUniqueID("1");
Thing thing2 = new Thing();
thing2.setUniqueID("2");
v.add(thing1);
v.add(thing2);
HashSet hs = new HashSet();
hs.addAll(v);
Thing thing3 = new Thing();
thing3.setID("2");
boolean flagFound = hs.contains(thing);
... flagFound returns false as hs.contains calls the Object.equals() method Not Thing's equals method.
My question:
How do I add a collection such that the function pointer of equals() method points to the derived class rather than the Object.equals() method (that just does a reference comparision).

you need to also override the hashCode method in your class:
public class Thing {
    public boolean equals() {
    public int hashCode() {
        return id;   // or something similar
}that's because the HashSet first uses the hashCode to find an object and then calls equals. If you don't override it, the object's address is used, so thing3 ends up with a different hashcode than thing2.
regards,
paris

Similar Messages

  • Java Collection addAll method parameters too restrictive

    Can anyone tell me why Java Sun does not allowed to add elements to Collection using addAll(List<?>) instead of addAll(List<? extends E>)?

    TNT wrote:
    It meant to prove that Yes, we can and we should allow addAll(List<?> c) instead of addAll(List<? extends E>) because the reasons I tries to explain here.No, we should not. It is correct as it is, for the reasons I stated. List<?> and List<Object> are effectively the same as far as this issue goes, and both +break compile-time type-safety* as I already demonstrated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to merge 2 Collections? . . .

    Hey All,
    Can anyone tell me the best way I can merge 2 Collections? I tried using the Collection.addAll(Collection c) method, but I get an UnsupportedOperationException.
    Thanks for any help in advance,
    Peter

    The Collection type is a proprietary type. The Collection I'm getting back comes from a call to a JDO (Java Data Objects) driver. I don't have the source code so I don't know exactly. I used reflection and called Class.getName() on the object only to get back an Object type that is a proprietary type written by the vendor.
    I also tried converting the Collections into arrays (using the Collection.toArrray() method) only to find out that the size of the array returned is sometimes less than the size of the Collection the array was generated from (I used Collection.size() to find out the size of the Collection). I was hoping to use System.arraycopy() to merge the 2 arrays returned from the 2 Collections.
    Any ideas?

  • BUG - OJC 10.1.3.2 doesn't allow upcast when adding to generic Collection

    JDeveloper: 10.1.3.2.0.4066
    Compile Errors:
    method asList(Crusty, Slush, Powder) not found in class java.util.Arrays
    method addAll(java.util.List<Snow>, Light, Heavy) not found in class java.util.Collections
    When adding a group of elements to a Collection which uses generics, the ojc compiler does not allow upcasting, but the same upcasting is permitted by the javac compiler.
    The following code is taken from Bruce Eckel's Thinking In Java, 4th edition, page 396. It reproduces the compile problems:
    import java.util.*;
    class Snow {}
    class Powder extends Snow {}
    class Light extends Powder {}
    class Heavy extends Powder {}
    class Crusty extends Snow {}
    class Slush extends Snow {}
    public class AsListInference {
      public static void main(String[] args) {
        //Following line compiles under javac but not under ojc:
        List<Snow> snow1 = Arrays.asList(new Crusty(), new Slush(), new Powder());
        System.out.println("snow1:");
        for (Snow s : snow1) {
          System.out.println(s);
        //Following line doesn't compile under javac or ojc:
        //List<Snow> snow2 = Arrays.asList(new Light(), new Heavy());
        List<Snow> snow3 = new ArrayList<Snow>();
        //Following line compiles under javac but not under ojc:
        Collections.addAll(snow3, new Light(), new Heavy());
        System.out.println("snow3:");
        for (Snow s : snow3) {
          System.out.println(s);
        //Following line compiles under both javac and ojc:
        List<Snow> snow4 = Arrays.<Snow> asList(new Light(), new Heavy());
        System.out.println("snow4:");
        for (Snow s : snow4) {
          System.out.println(s);
    }

    Loren,
    thanks will file this too
    Frank

  • Problem in factory method, how to pass arguments ?

    Hello it's me again :)
    here's the code :
    package print;
    import java.util.*;
    import static print.Print.*;
    interface Fact<T> {
    T create(String n);;
    T create ();
    class PetColl {
          public String toString() {
          return getClass().getSimpleName();
          static List<Fact<? extends Pet>> petSpecies=
          new ArrayList<Fact<? extends Pet>>();
          static {
          // Collections.addAll() gives an "unchecked generic
          // array creation ... for varargs parameter" warning.
               petSpecies.add(new Cymric.Factory());
               petSpecies.add(new EgyptianMau.Factory());
               petSpecies.add(new Hamster.Factory());
               petSpecies.add(new Manx.Factory());
               petSpecies.add(new Mouse.Factory());
               petSpecies.add(new Pug.Factory());
               petSpecies.add(new Mutt.Factory());
               petSpecies.add(new Rat.Factory());
          private static Random rand = new Random(47);
          public static Pet createRandom() {
          int n = rand.nextInt(petSpecies.size());
          return petSpecies.get(n).create();
          public Pet[] createArray(int size) {
               Pet[] result = new Pet[size];
               for(int i = 0; i < size; i++)
               result[i] = createRandom();
               return result;
          public ArrayList<Pet> arrayList(int size) {
               ArrayList<Pet> result = new ArrayList<Pet>();
               Collections.addAll(result, createArray(size));
               return result;
    class Individual implements Comparable<Individual> {
         private static long counter = 0;
         private final long id = counter++;
         private String name;
         public Individual(String name) { this.name = name; }
         // ?name? is optional:
         public Individual() {}
         public String toString() {
         return getClass().getSimpleName() +
         (name == null ? "" : " " + name);
         public long id() { return id; }
         public boolean equals(Object o) {
         return o instanceof Individual &&
         id == ((Individual)o).id;
         public int hashCode() {
         int result = 17;
         if(name != null)
         result = 37 * result + name.hashCode();
         result = 37 * result + (int)id;
         return result;
         public int compareTo(Individual arg) {
         // Compare by class name first:
         String first = getClass().getSimpleName();
         String argFirst = arg.getClass().getSimpleName();
         int firstCompare = first.compareTo(argFirst);
         if(firstCompare != 0)
         return firstCompare;
         //second compare by name
         if(name != null && arg.name != null) {
         int secondCompare = name.compareTo(arg.name);
         if(secondCompare != 0)
         return secondCompare;
         }//third compare by id
         return (arg.id < id ? -1 : (arg.id == id ? 0 : 1));
    class Pets {
          public static final PetColl creator =
          //new LiteralPetCreator();
               new PetColl();
          public static Pet randomPet() {
          return creator.createRandom();
          public static Pet[] createArray(int size) {
          return creator.createArray(size);
          public static ArrayList<Pet> arrayList(int size) {
          return creator.arrayList(size);
    class Person extends Individual {
    String name;
    public static class Factory implements Fact<Person>{
    public Person create(String name){
         Person.name=name;
         return new Person(); }
    public Person create(){return new Person();}
    class Pet  extends Individual {
    class Dog extends Pet {
    class Mutt extends Dog {
          public static class Factory implements Fact<Mutt> {
               public  Mutt create(String name){return new Mutt(name);}
               public  Mutt create () {return new Mutt();}
    class Pug extends Dog {
          public static class Factory implements Fact<Pug> {
               public  Pug create(String name){return new Pug(name);}
               public  Pug create () {return new Pug();}
    class Cat extends Pet {
    class EgyptianMau extends Cat {
          public static class Factory implements Fact<EgyptianMau> {
               public  EgyptianMau create(String name){return new EgyptianMau(name);}
               public  EgyptianMau create () {return new EgyptianMau();}
          class Manx extends Cat {
               public static class Factory implements Fact<Manx> {
                    public  Manx create(String name){return new Manx(name);}
                    public  Manx create () {return new Manx();}
         class Cymric extends Manx {
              public static class Factory implements Fact<Cymric> {
                    public  Cymric create(String name){return new Cymric(name);}
                    public  Cymric  create () {return new Cymric();}
    class Rodent extends Pet {
    class Rat extends Rodent {
          public static class Factory implements Fact<Rat> {
               public  Rat create(String name){return new Rat(name);}
               public  Rat create () {return new Rat();}
    class Mouse extends Rodent {
          public static class Factory implements Fact<Mouse> {
               public  Mouse create(String name){return new Mouse(name);}
               public  Mouse create () {return new Mouse();}
    class Hamster extends Rodent {
          public static class Factory implements Fact<Hamster> {
               public  Hamster create(String name){return new Hamster(name);}
               public  Hamster create () {return new Hamster();}
    public class Test {
          public static void main(String[] args) {
              for(Pet p:Pets.creator.arrayList(25)){
          PetCount.petC.count(p.getClass().getSimpleName());
              print(p.getClass().getSimpleName());}
      class PetCount {
          static class PetCounter extends HashMap<String,Integer> {
          public  void count(String type) {
          Integer quantity = get(type);
          if(quantity == null)
          put(type, 1);
          else
          put(type, quantity + 1);
         public static PetCounter petC= new PetCounter();
      }and here's my problem:
    I'm trying to fill up list using factory method but in a fact that I want to have two constructors, I have a problem to set field name of objects of those classes. Is there any possibility to use in that way some factory method to create that list ?
    In Person class I've tried to set it in factory method before creating an object, but as you know that option is only alvailable for static fields which i don't want to be static.

    I for one have no idea what you're asking, and what you seem to be saying doesn't make sense.
    I'm trying to fill up list using factory method but in a fact that I want to have two constructors,Two constructors for what? The factory class? The classes that the factory instantiates?
    I have a problem
    to set field name of objects of those classes. Is there any possibility to use in that way some factory method to
    create that list ?What?
    In Person class I've tried to set it in factory method before creating an object, but as you know that option is only alvailable for static fields which i don't want to be static.That doesn't make any sense. A Factory can easily set fields in the objects it creates on the fly (not static).

  • Leading zero is kept in arraylist ---

    Hello,
    Running the program below should remove all zeros from an arraylist; yet, the leading zero still appears in the output. Any explanation would be most helpful ... Thanks
    import java.util.ArrayList;
    public class Example
    public static ArrayList<Integer> nums = new ArrayList<Integer>();
    public static void numQuest()
    int k = 0;
    Integer zero = new Integer(0);
    nums.add(0);
    nums.add(0);
    nums.add(4);
    nums.add(2);
    nums.add(5);
    nums.add(0);
    nums.add(3);
    nums.add(0);
    while ( k < nums.size())
    if (nums.get(k).equals(zero))
    nums.remove(k);
    k++;
    System.out.print("contents of nums: " + nums );
    System.out.print("\n");
    public static void main (String[] args)
    numQuest();

    import java.util.*;
    public class Example {
        public static void main (String[] args) {
            List<Integer> numbers = new ArrayList<Integer>();
            Collections.addAll(numbers, 0, 0, 4, 2, 5, 0, 3, 0);
            System.out.println("before: " + numbers);
            numbers.removeAll(Arrays.asList(0));
            System.out.println("after: " + numbers);
    }looping over a collection while removing elements (which shifts the rest up) is a bad idea, unless you are going backwards from end to beginning.
    But using removeAll is even easier!
    The manual solution is to use an iterator and its remove method:
    import java.util.*;
    public class Example {
        public static void main (String[] args) {
            List<Integer> numbers = new ArrayList<Integer>();
            Collections.addAll(numbers, 0, 0, 4, 2, 5, 0, 3, 0);
            System.out.println("before: " + numbers);
            for(Iterator<Integer> i = numbers.iterator(); i.hasNext(); ) {
                if (i.next().equals(0)) {
                    i.remove();
            System.out.println("after: " + numbers);
    }

  • Joining two lists

    Hi,
    Let's say I have a class Car
    public class Car{
      private int id;
      private String make;
      private String model;
      //getters and setters
    }Now I'm going to some db and fill a List<Car>,
    List<Car> results1 = getCarsFromDB(String someCriteria);and I do the same but this time I'm going to another db,
    List<Car> results2 = getCarsFromAnotherDB(String someCriteria);What I want is to create a list with the two results lists. Using contains method from List doesn't work because the objects are different although the have the same data. Is there a simple way of joining this? (in my example, two objects are equal if they have the same idthanks in advance,
    Manuel Leiria

    ok, I have now an equals and hashCode method in my
    Car but I can't see how the Collections.addAll can
    help me! When joining the two lists in a resultlist,
    at some point I must compare the Car objects. Am I
    wrong?
    thanks,
    Manuel leiriaso if I understand you, you're trying to merge 2
    collections, and avoid duplicates? sounds like a job
    for Sets, then!yes, I've changed my final list to a set. It's better
    thanks,
    Manuel Leiria

  • Looping through serialized objects?

    I have made a program which stores the game score such as seen 3d pinball. I know how to store then but I don't know how to loop through all records so that I can store them in one single array so that I can perform diffenent operations on that array.
    such I should arrange them and find out the top five scorer. Give me some valueable hints.

    Demo:
    import java.io.*;
    import java.util.*;
    public class Example implements Serializable {
        private static final long serialVersionUID = 1;
        private String text;
        public Example(String text) {
            this.text = text;
        public String toString() {
            return text;
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            List<Example> list = new ArrayList<Example>();
            Collections.addAll(list, new Example("hello"), new Example("world"));
            File file = new File("temp.dat");
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
            out.writeObject(list);
            out.flush();
            out.close();
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
            List<Example> input = (List<Example>) in.readObject();
            in.close();
            System.out.println(input);
    }

  • Setting styleable properties & pseudo-class state to controls in JavaFX 2.2

    Hi All,
    Greetings!
    Can anyone please let me know how to create or set styleable and pseudo-class state properties for custom controls developed with JavaFX 2.2.
    I found a very nice wiki regarding this. (https://wikis.oracle.com/display/OpenJDK/CSS+API+to+support+custom+UI+Controls)
    But this seems to be with JavaFX 8 version. As i cannot find PseudoClass in the current version of JavaFX 2.2.
    Thanks & Regards,
    Sai Pradeep Dandem.

    There is no public API in 2.2 for adding adding styleable properties and pseudo-class state to controls in JavaFX 2.2.
    The implementation between 2.2 and 8.0 changed significantly in terms of API, class names, etc. The model is roughly the same, but if you implement something in 2.2 using the private implementation APIs, it will not work, and may not even compile, in 8.0.
    // A pseudo-class in 2.2
        private BooleanProperty foo = new BooleanPropertyBase() {
                    @Override
                    protected void invalidated() {
                        impl_pseudoClassStateChanged("foo");
                    @Override
                    public Object getBean() {
                        return MyControl.this;
                    @Override
                    public String getName() {
                        return "foo";
        public boolean isFoo() {
            return foo.get();
        public void setFoo(boolean newFoo) {
            foo.set(newFoo);
        private static final long FOO_PSEUDOCLASS_STATE = StyleManager.getInstance().getPseudoclassMask("foo");
        @Override
        public long impl_getPseudoClassState() {
            long mask = super.impl_getPseudoClassState();
            if(isFoo()) mask |= FOO_PSEUDOCLASS_STATE;
            return mask;
    // A styleable property in 2.2. import classes from com.sun.javafx.css
            public DoubleProperty bar = new StyleableDoubleProperty(0.0) {
                        @Override
                        public StyleableProperty getStyleableProperty() {
                            return BAR;
                        @Override
                        public Object getBean() {
                            return MyControl.this;
                        @Override
                        public String getName() {
                            return "bar";
    // API used by css in 2.2
            private static final StyleableProperty<MyControl,Number> BAR =
                new StyleableProperty<MyControl,Number>("-my-bar",
                    SizeConverter.getInstance(), 0.0) {
                    @Override
                    public boolean isSettable(MyControl ctl) {
                        return bar.isBound() == false;
                    @Override
                    public WritableValue<Number> getWritableValue(MyControl ctl) {
                        return ctl.bar;
             private static final List<StyleableProperty> STYLEABLES;
             static {
                 final List<StyleableProperty> styleables = new ArrayList<StyleableProperty>();
                 Collections.addAll(styleables,
                     BAR
                 STYLEABLES = Collections.unmodifiableList(styleables);
         public static List<StyleableProperty> impl_CSS_STYLEABLES() {
             return STYLEABLES;
        public List<StyleableProperty> impl_getStyleableProperties() {
            return impl_CSS_STYLEABLES();
        }

  • Trying to Caclulate all subsets of a List

    So my problem is trying to figure out all subsets of a given list
    here the code i have:
    public static <T> Set<Set<T>> getSubsets(List<T> list) {
              if(list.size() == 1){
                   Set<Set<T>> r = Collections.synchronizedSet(new HashSet<Set<T>>());
                   Set<T> s = Collections.synchronizedSet(new TreeSet<T>());
                   s.add(list.get(0));
                   r.add(s);
                   r.add(new TreeSet<T>());
              return r;
              }else{
                   Set<Set<T>> t = getSubsets(list.subList(1, list.size()));
                   for(Set<T> m : t){
                        TreeSet<T> tmp = new TreeSet<T>(m);
                        tmp.add(list.get(0));
                        t.add(tmp);
                   return t;
    but when i run this, i get a
    java.util.ConcurrentModificationException
         at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
         at java.util.HashMap$KeyIterator.next(Unknown Source)
         at genericLists.Recursion.getSubsets(Recursion.java:62)
         at genericLists.Recursion.getSubsets(Recursion.java:59)
         at tests.studentTests.testSubsets(studentTests.java:13)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at junit.framework.TestCase.runTest(TestCase.java:168)
         at junit.framework.TestCase.runBare(TestCase.java:134)
         at junit.framework.TestResult$1.protect(TestResult.java:110)
         at junit.framework.TestResult.runProtected(TestResult.java:128)
         at junit.framework.TestResult.run(TestResult.java:113)
         at junit.framework.TestCase.run(TestCase.java:124)
         at junit.framework.TestSuite.runTest(TestSuite.java:232)
         at junit.framework.TestSuite.run(TestSuite.java:227)
         at org.junit.internal.runners.OldTestClassRunner.run(OldTestClassRunner.java:76)
         at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
         at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
    any ideas of getting around this?
    Thanks
    -Rahul
    Edited by: Rahulm5000 on Apr 15, 2009 3:40 PM

    Recursively:
    import java.util.*;
    public class PowerTest {
        public static void main(String[] args) {
            Set<String> words = new LinkedHashSet<String>();
            Collections.addAll(words, "a", "b", "c", "d");
            System.out.println(powerSet(words));
        static <T> Set<Set<T>> powerSet(Set<T> s) {
            return recursivePow(new ArrayList<T>(s));
        //gradually empties s!
        private static <T> Set<Set<T>> recursivePow(List<T> s) {
            Set<Set<T>> pow = new LinkedHashSet<Set<T>>();
            if (s.isEmpty()) {
                pow.add(new LinkedHashSet<T>());
            } else {
                T t = s.remove(0);
                for(Set<T> subset: recursivePow(s)) {
                    pow.add(subset);
                    pow.add(plus(subset, t));
            return pow;
        //helper method
        static <T> Set<T> plus(Set<T> x, T t) {
            Set<T> y = new LinkedHashSet<T>(x);
            y.add(t);
            return y;
    }

  • How to Merge the elements of two separate lists into a single one .

    Hi ,
    I am unable to add elemnts of 2 separate Lists suppose list1= { HashmapA, HashMapB}
    List2 = { HashmapC, HashMapD } into the third list List3 whose elements should be
    { HashmapA, HashMapB,HashmapC, HashMapD } .
    I am trying Collections.addAll(List3 ,List2 ,list1)
    but it is giving me a list whose elements are 2 lists( 0 -> list1,1->list2) and not { HashmapA, HashMapB,HashmapC, HashMapD }.
    Can anyone help me out with this !!!!!

    I am unable to add elemnts of 2 separate Lists suppose list1= { HashmapA, HashMapB}
    List2 = { HashmapC, HashMapD } into the third list List3 whose elements should be
    { HashmapA, HashMapB,HashmapC, HashMapD } .
    You can also try
    Set<T> union = new HashSet<T>(list1);
    union.addAll(list2);Assuming you want to get rid of the duplicates. Replace T with the actual type of your elements.

  • JList  getSelectedValues to a Vector

    Hi out there,
    i am a new java developer and what i am trying to do is to get the selected values of a MULTIPLE_INTERVAL_SELECTION JList and put all these selected values into a Vector.
    Something like this:
    Vector Vec = new Vector();
    Vec.add(jList1.getSelectedValue());
    but i need to take all selected values and place them in the vector.
    I am trying some ways but not having fun
    thanks for helping.
    []s
    Ludwig

    get a API and always refer to [url http://java.sun.com/j2se/1.4.2/docs/api/]API when you are not sure of something. You can download it too...
    the JList can get all the selected values. Refer to this
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JList.html#getSelectedValues()
    while
    [url http://java.sun.com/j2se/1.4.2/docs/api/java/util/Arrays.html#asList(java.lang.Object[])]
    Arrays.asList()help you to convert array to a List
    and [url http://java.sun.com/j2se/1.4.2/docs/api/java/util/List.html]List was extented Collection
    where you can use [url http://java.sun.com/j2se/1.4.2/docs/api/java/util/Vector.html#addAll(java.util.Collection)]addAll method in vector to add all selected item to your vector.

  • Adding to a Collection using JDBC

    I'm trying to add to a Collection via JDBC but have had no luck with getting the ResultSet into the Collection and would be grateful for some pointers in the right direction in the while (rs.next()) block:
    public void getMembers(BwGroup group) throws CalFacadeException {
         Class.forName("com.mysql.jdbc.Driver");
         String url = "jdbc:mysql://localhost/loginlist";
         Connection conn = null;
         Collection<BwPrincipal> ms = new TreeSet<BwPrincipal>();
          try {
             conn = DriverManager.getConnection(url, "user", "pword");
             PreparedStatement ps = conn.prepareStatement("SELECT * FROM list WHERE list='" + group +"'");
             ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                   BwPrincipal = new bp(rs.getString(1));
                   ms = addAll(bp);
               group.setGroupMembers(ms);
               rs.close();
               ps.close();
               } catch (Exception e){
                e.printStackTrace();
               } finally {
             if (conn != null) {
            conn.close();
        }I'm getting errors regarding incompatible types for the BwPrincipal line and addAll being an unfound symbol (though I had thought that it was a method to add to Collections). If I try to call BwPrincipal as BwPrincipal bp = new bp(rs.getString(1)); then the addAll error disappears but the programme cannot see BwPrincipal as a class. I feel as if I'm going around in circles at the moment.

    BaroqueThoughts wrote:
    As you say, I'm trying to call something along the lines of
    ms= rs.getString(1);but get an incompatible string back. The reading that I had done suggested addAll but I've probably misunderstood in trying to get this to work. If I try
    ms.add(rs)then the compiler doesn't like the add method (add cannot be applied to java.sql.ResultSet)Well it can't. Why did you try that, though? To be honest, if you can't figure this out yet, JDBC is probably a step too far at the moment. Re-visit the basics, because you clearly don't understand them yet, and you'll struggle forever if you carry on down this path as-is

  • How can I override addAll method in LineChart ?

    Hi,
    I need to add some statement when the methods add or addAll are invoked in linechart. How can I do ?
    I thought to do an override of the method, like this
    public boolean addAll(Collection<? extends E> es) {   
            return super.addAll(es);
            <  ..some new statement... >
    but something is wrong.

    'return' returns immediately from your method, so the remaining statements can't be reached. Do
    public boolean addAll(Collection<? extends E> es) {  
            //<  ..some new statement... >
            return super.addAll(es);
    or
    public boolean addAll(Collection<? extends E> es) {  
            boolean result =  super.addAll(es);
            // <  ..some new statement... >
            return result ;

  • Object Array --- Collection

    Is there any way to directly convert and object Array to a Collection object. Basically i need to create a ArrayList from Object Array. The ArrayList has a constructor and also provides a method addAll() that accept Collection as parameter. So the problem becomes , how to convert Object Array to collection. As per my understanding all arrays should be essentially Collection Interface subclass.
    So why am i not able to cast?
    What is wrong in calling Object Array a sub class of Collection?
    // OrderLineItem[] is the object array that i wish to have as ArrayList
    // This code generates error -
    //"ErpOrder.java": Error #: 364 : cannot cast gal.ERP.OrderLineItem[] to java.util.Collection
      public void setLineItems( OrderLineItem[] arrOrderLineItem ) {
        m_arrLineItems = new ArrayList((Collection)arrOrderLineItem);
      }Is there no way except iterating through the array and adding individual Objects to ArrayList?

    By "Object array" do you mean an Array class, or do you mean an Object[]? They are different. The Array class wraps an Object[] and provides useful methods to manipulate it.
    There is no such thing as a Collection object, per say. "Collection" is an interface implemented by many objects such as LinkedList, Vector, ArrayList, HashSet, and TreeSet.
    The Collection interface is designed to be an interface to any object that can keep a mutable list of other Objects, check to see if an Object is in that list, and iterate through all Objects in the list.
    As far as resources go, I suggest the API reference at http://java.sun.com/j2se/1.4.1/docs/api/index.html.

Maybe you are looking for