public class GWC { public static void mstd(ArrayList<P> lst) { P o = lst.get(0); lst.add(new C2()); } public static void mspec(ArrayList<? extends P> lst) { P o = lst.get(0); // syntax error - for good reasons: we can not add a C2 to this list //lst.add(new C2()); } public static void main(String[] args) { // basic ArrayList<P> lst1 = new ArrayList<P>(); lst1.add(new C1()); mstd(lst1); // problem ArrayList<C1> lst2 = new ArrayList<C1>(); lst2.add(new C1()); // syntax error - for good reasons: we can not add a C2 to this list //mstd(lst2); // solution mspec(lst2); } }
Mange tak for hjælpen arne_v. Skal nemlig have det som emne i min uddannelse senere i semestret.
Men nu har jeg et nyt problem. Måske du kan hjælpe mig?
Jeg har fået en opgave vedr. Hashset. som lyder på : In this exercise you're going to use the java.util.Hashset Class for storage and retrival of data in files on a disk.
Problemet her når jeg tilføjer 3 instancer af Person til HashSet og vil skrive til file kommer denne her fejl : Output: The_Use_Of_Hashset.Person@1eed786 3.1415 The_Use_Of_Hashset.Person@19f953d true 4910 The_Use_Of_Hashset.Person@1fee6fc java.io.NotSerializableException:
private Person peter = new Person("Peter", "010364-1777", "188 cm"); private Person poul = new Person("Poul", "231064-5641", "180 cm"); private Person mary = new Person("Mary", "170765-4242", "161 cm"); public Saver() {
Set<Object> obj = new HashSet<Object>();
obj.add(new Integer(4910)); obj.add(new Double(3.1415)); obj.add(new Boolean(true)); //Adding the objects to the HashSet obj.add(new Integer(491*10)); obj.add(peter); obj.add(poul); obj.add(mary);
//printing the obj System.out.println("----Printing set----"); for(Object o : obj) System.out.println(o.toString()); // Iterator<Object> itr = obj.iterator(); // while (itr.hasNext()) { // Object o = itr.next(); // // System.out.println(o); // } if (obj.contains(peter)&& obj.contains(mary)){ System.out.println("Person found"); }else{ System.out.println("Cannot find person"); } try { FileOutputStream fos = new FileOutputStream("object", false);
ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(obj); oos.close(); } catch (FileNotFoundException e) { System.out.println("Uable to write to Objects"); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
} Min Output ser mærkelig ud? ---Printing set---- The_Use_Of_Hashset.Person@12dacd1 The_Use_Of_Hashset.Person@e48e1b 3.1415 true 4910 The_Use_Of_Hashset.Person@1ad086a Person found
----Print the Loadet file <object.txt>---- Number of Elements in HashSet 6 The_Use_Of_Hashset.Person@1754ad2 3.1415 true The_Use_Of_Hashset.Person@1833955 4910 The_Use_Of_Hashset.Person@e86da0
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.