[JAVA] ArrayList in TreeSet umwandeln

taks

PCGH-Community-Veteran(in)
Abend zusammen

Ich komm hier irgendwie nicht vom Fleck -.-

Ich habe eine ArrayList(SampleLists.getPersonsList1()) welche ich in ein TreeSet übergeben will, damit ich die Elemente sortieren kann.
Jedoch bringt er mir immer dass ich die Liste nicht in einen Tree umwandeln kann, da der Tree nicht comparable ist.

Hat eine ne Idee wie man das machen kann?


Gruss und Danke



Test.java schrieb:
System.out.println(CollectionFunctions.median(SampleLists.getPersonList1()));

SampleLists.java schrieb:
public static List<Person> getPersonList1() {
List<Person> persons = new ArrayList<Person>();
persons.add(new Person...);
return persons;
}

CollectionFunctions.java schrieb:
public static<E> Collection<E> median(Collection<E> coll) {

SortedSet<E> midHash = new TreeSet<E>(coll);
int size = midTree.size();

return null;
}
 
Wenn du wirklich nur die ArrayList sortieren willst solltest du dir mal das Comparator Interface und die Collections.sort Funktion anschauen.

Beispiel:

Code:
public class ArrayListSortTest {
	
	private static class Person {
		public String name;
		
		public Person(String name) {
			this.name = name;
		}
	}
	
	public static void main(String[] args) {
		List<Person> l = new ArrayList<Person>();
		l.add(new Person("Frank"));
		l.add(new Person("Alfred"));
		l.add(new Person("Chris"));
		l.add(new Person("Bernd"));
		
		Collections.sort(l, new Comparator<Person>() {
			@Override
			public int compare(Person a, Person b) {
				return a.name.compareTo(b.name);
			}
		});
		
		for (Person p : l) {
			System.out.println(p.name);
		}
	}
}
 
Zurück