Create a shared array of an inner class

The line in which I create the array gives me a warning Generic array creation. What is a good way to handle this?

public class Foo<T> {

    void someMethod() {
        Point[] points = new Point[3];
    }

    class Point {
        float x, y;
    }
}
+4
source share
4 answers

First, let's find out why Java thinks it new Point[3]creates a common array, and Pointnot a common class. This is because it Pointis a non-static class, which means that it contains a hidden link to a Foo<T>built-in compiler. The class looks like this: Java:

class Foo$Point<T> {
    Foo<T> _hidden_Foo;
    float x, y;
}

Foo$, <T> _hidden_Foo , , , Point Foo<T>.

:

  • static Point, , , . . ajb. Point Foo<T> members
  • static , List<Point> , . , .

:

public class Foo<T> {
    void someMethod() {
        List<Point> points = new ArrayList<Point>();
        ... // add three points to the list
    }
    class Point {
        float x, y;
    }
}
+8

, Point x y, Foo<T>. , Point , . static:

public class Foo<T> {

    void someMethod() {
        Point[] points = new Point[3];
    }

    static class Point {
        float x, y;
    }
}
+3

. ,

class Foo<T> {

    class Point {
        float x, y;
        T value;
        T getValue(){
            return value;
        }
    }
}

Foo

Foo<String> f = new Foo<>();

,

Point p = f.new Point();
// or 
//Foo<String>.Point p = f.new Point 
// if we are creating it for instance outside of Foo class

, p.getValue() String, p.getValue().charAt(0).

, generic type , , :

  • T[size].
  • Foo<T>[size]
  • Foo<T>.Point[size]

- ,

Point[] points = new Point[3];

Point[] points = new Foo<T>.Point[3];
//  Foo<T> is type of outer instance on which you are invoking new

.

  • , ,

    Point[] points = new Foo.Point[3];// we got rid of <T>
    

    , .

  • , , List<Point>.

    List<Point> points = new ArrayList<>();
    
  • , , T Foo. static, , , , .

    static class Point {
        float x, y;
    }
    

    Point[] points = new Point[3]; 
    

    .

+2

Point - . , Point, , Foo<T>.Point, . new Point[3] ( , new Foo<T>.Point[3]), , new ArrayList<T>[3].

, , ​​ ,

ArrayList<T>[] lists = new ArrayList<T>[3];

:

  • :

    ArrayList<T>[] lists = new ArrayList[3];

  • , , :

    ArrayList<T>[] lists = (ArrayList<T>[])new ArrayList<?>[3];

, :

  • . , ? Point, ; . : Foo.Point:

    Point[] points = new Foo.Point[3];

  • , , :

    Point[] lists = (Point[])new Foo<?>.Point[3];

0

All Articles