Generics help needed
14/05/2018 12:08
Can someone explain how to get rid of the following warnings? Here isa 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.


Source is Usenet: comp.lang.java.help
Sign in to add a comment

Answer score: 5
14/05/2018 12:08 - 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> (orComparable<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

Source is Usenet: comp.lang.java.help
Sign in to add a comment

Answer score: 5
14/05/2018 12:08 - Bingo, that's the concept I was missing. Many thanks.


Chris Uppal <chris.uppal@metagnostic.REMOVE-THIS.org> writes:


Source is Usenet: comp.lang.java.help
Sign in to add a comment

eDiscover
Helpforce eDiscover provides technical articles updated each dayHelpforce eDiscover RSS feed contains the latest technical articles in RSS
Click the logo to go back to the main page
Search eDiscover
  
Categories

Click an icon to go to that category

Helpforce eDiscover contains articles about Microsoft Windows Helpforce eDiscover contains articles about Apple products and MacOS Helpforce eDiscover contains articles about Linux and POSIX operating systems Helpforce eDiscover contains articles about Helpforce Helpforce has a large variety of technical information and articles for you to read Helpforce eDiscover contains articles about databases, MYSQL, SQL Server Oracle Helpforce eDiscover contains articles about Java, JVM and the JRE Helpforce eDiscover contains articles about the QNX operating system Helpforce eDiscover contains articles about Oracle Solaris and Open Solaris Helpforce eDiscover contains articles about RISC OS, Acorn and the BBC Micro Helpforce eDiscover contains articles about Amiga and AmigaOS

Type your comment into the box below