-2

I've been working for my final essay, building a Java program to implement a K-means algorithm, and I got stuck on this error:

object cannot be converted to point.

And this is code where my error is

public void plotCluster() {
    System.out.println("[Cluster: " + id+"]");
    System.out.println("[Centroid: " + centroid + "]");
    System.out.println("[Points: \n");
    for(Point p : points) { // error
        System.out.println(p);
    }
    System.out.println("]");
}
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Please add your code where you declare points variable – Tran Vinh Quang Jul 27 '17 at 04:06
  • this one ? `public List points; public Point centroid; public int id;` – Surya Handika Jul 27 '17 at 04:12
  • Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: at javaapplication1.Point.createRandomPoints(Point.java:65) at javaapplication1.KMeans.init(KMeans.java:40) at javaapplication1.KMeans.main(KMeans.java:33) C:\Users\SISWA\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 1 second) – Surya Handika Jul 27 '17 at 04:16
  • 2
    Do you declare the list with a type parameter `<` `>`? Like `List` ? – Greg Kopff Jul 27 '17 at 04:16
  • https://stackoverflow.com/questions/858572/how-to-make-a-new-list-in-java – Eric Jul 27 '17 at 04:17
  • Greg is right, you are declaring 'points' incorrectly. – Eric Jul 27 '17 at 04:18
  • 1
    @SuryaHandika , please update your question with complete code – Amit Jul 27 '17 at 04:18
  • 1
    List myList = new ArrayList(); – Eric Jul 27 '17 at 04:20
  • 1
    @Eric yeah, but just make it `List myList = new ArrayList<>()` –  Jul 27 '17 at 04:26
  • 1
    Possible duplicate of [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Tom Jul 30 '17 at 07:20

1 Answers1

4

From you comment, you mention that you declare your list like this:

public List points;

and I'll assume that later, you do:

points = new ArrayList();

A List is a generic class, and the type parameter says what type of object the list holds. If you don't specify the type parameter, it defaults to Object.

You should declare your list with the type parameter:

public List<Point> points;

points = new ArrayList<>();           // note the <>

In your current code, you've got a raw list (defaulting to holding Object), and that's why for(Point p : points) fails to type check. As far as the compiler is concerned, the list holds Object and thus you cannot assigned it to p which has type Point.

Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
  • Darn! I was in the middle of my answer when I got sidetracked! I was going to say the same thing. Oh well. Nice answer! (+1) –  Jul 27 '17 at 04:24