generics help needed

R

Rusty Wright

Can someone explain how to get rid of the following warnings? Here is
a simple contrived example. The warnings are when I call sort().

Here is the sample code:

import java.util.*;

class Xyz {
private List<Xyz> xlist = new ArrayList<Xyz>();

public void abc() {
xlist.add(new Xyz());

Collections.sort((List) xlist);
}
}

Here are the warnings I get about sort():

Xyz.java:9: warning: [unchecked] unchecked conversion
found : java.util.List
required: java.util.List<T>
Collections.sort((List) xlist);
^
Xyz.java:9: warning: [unchecked] unchecked method invocation: <T>sort(java.util.List<T>) in java.util.Collections is applied to (java.util.List)
Collections.sort((List) xlist);
^
2 warnings

Thanks.
 
C

Chris Uppal

Rusty said:
class Xyz {
private List<Xyz> xlist = new ArrayList<Xyz>();

public void abc() {
xlist.add(new Xyz());

Collections.sort((List) xlist);

Why the cast to (List) ? Collections.sort is a generic operation nowadays.

I think that either you have to make class Xyz implement Comparable<Xyz> (or
Comparable<something that includes Xyz-s>, and then just say:

Collections.sort(xlist);

Or else use the other flavour of Collection.sort() that takes a list of
<anything> plus a custom Comparator<>.

-- chris
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,787
Messages
2,569,627
Members
45,328
Latest member
66Teonna9

Latest Threads

Top