0

I would like to create a Pair of String's and a List of String's.

I created my own class of Pair<String, List<String>>. However, when I tried to compile, it complained about the brackets. What should I do to get rid of this error?

error: > expected
    static class Pair<String, List<String>> {
                                  ^
Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
  • Possible duplicate of [Java: how do I get a class literal from a generic type?](https://stackoverflow.com/questions/2390662/java-how-do-i-get-a-class-literal-from-a-generic-type) – Yoshikage Kira Sep 15 '19 at 23:44
  • 2
    To get better help use [edit] option and include [MCVE] (a.k.a. [SSCCE](http://sscce.org)) so we would be able to copy-paste it to our machines and without any modifications reproduce precise problem you are having. – Pshemo Sep 15 '19 at 23:47
  • 1
    Welcome to SO. If you are trying to create a class `Pair` that contains a `String` and a `List` then those classes don't need to be in the class name. Just declare two variables with those types inside your class. – sprinter Sep 16 '19 at 00:10
  • Why you are not using map>. If there is a unique key – Vimit Dhawan Sep 16 '19 at 04:55

1 Answers1

2

First of all, I asume that this Pair class is a static nested class, if it isn't even if the Generic declaration would be Ok, it will still not compile because a top level class cannot be static.

This is a wrong syntax on how to declare a generic class.

When you are creating generic classes you don't need to specify the type of the class it will be because that would not be generic and it looses the whoole purpose of it, so the compiler will not allow it.

Having said this, for your code to works fine and compile it would be something like the following:

import java.util.List;

public class Pair<T,S>{

    private T t;
    private S s;

    //add revelevant code here

    public static void main(String[] args){
        //When instantiating the class you declare the generics types you want to use, in
        //your case String,List<String>
        Pair<String,List<String>> pair = new Pair<>();

        //Since Java 7 we can use diamond operator <> in instantiation to infer the 
        //generic type otherwise it would be like this.
        Pair<String,List<String>> otherPair = new Pair<String,List<String>>();

    }

}

If you have any more doubts about generics in java, please visit https://docs.oracle.com/javase/specs/ and find the Java Specification Language for the desired Java version and check the generics section.

Have a good day!

ajvasquez000
  • 56
  • 1
  • 4