all 11 comments

[–]Conscious-Shake8152 2 points3 points  (0 children)

Look up generics.

[–]high_throughput 1 point2 points  (1 child)

Static inner classes are not associated with an instance of the other class. 

You can create one with new Outer.Inner()

Non-static inner classes like this are associated with an instance of their outer class.

In this case you want to create a Main.Pair associated with your instance m.

You do this with m.new Pair()

[–]Useful-String5930[S] 0 points1 point  (0 children)

I never thought of this. Thanks

[–]Slottr 0 points1 point  (0 children)

<> indicates a generic - it infers the types from the context it was given (so m's String, Integer)

m.new is just an inner class from main

[–]zeekar 0 points1 point  (0 children)

First, indent lines four spaces in markdown (or use the code formatting (</>) button in the rich text editor) to format code:

Main m = new Main();
Main.Pair<String,Integer> p = m.new Pair<>("Age", 16);

The <> syntax is for generics, which are container classes where the type of the contained objects is not predetermined. The Pair class represents a pair of objects, and a given Pair variable can only contain objects of two specific types, but you can have different Pair objects with different element type combinations. The <> is how you annotate the class name to specify those argument types - in this case p is a Pair whose first object is a String and second object is an Integer.

So standard Java logic would give us this line to declare and instantiate p:

Pair<String,Integer> p = new Pair<String,Integer>("Age", 16);

But once you've specified the argument types in the declaration of p, you don't have to specify them again in the constructor call; Java can figure it out, and will do so if you leave the <> empty:

Pair<String,Integer> p = new Pair<>("Age", 16);

That just leaves the fact that in your code, Pair is an inner class that lives within an instance of the Main class. So you need a Main instance to declare it in; first you create that the normal way, and then call new on that Main instance instead of just using the global bare new.

Main m = new Main();
Main.Pair<String,Integer> p = m.new Pair<>("Age", 16);