Kamilski81
Kamilski81

Reputation: 15127

How do I instantiate a BigInteger in a java static method like this?

I don't understand what I'm doing wrong here because I get an error: 'Cannot instantiate the type BigInteger'

public static <BigInteger> List<BigInteger> convertIntegerListToStringList(List<String> existingList) {
      ArrayList<BigInteger> newList = new ArrayList<BigInteger>();
      for(String item : existingList) {
        newList.add(new BigInteger(item));
      }
      return newList    
}

the part that is breaking the code is the public static <BigInteger> type parameter...but I have no idea why. When i remove this typed parameter then the compilation error goes away.

Upvotes: 0

Views: 934

Answers (3)

Mike Strobel
Mike Strobel

Reputation: 25623

Remove the lone <BigInteger> from your method signature. That syntax is for declaring type variables, which is not necessary in your case. As written, you are declaring a "placeholder" called BigInteger that represents some unknown type. Within the method, BigInteger refers to that unknown type (which, being unknown, cannot be instantiated) instead of referring to java.math.BigInteger as you intended.

Also, you should revisit your method name: your method performs the opposite operation that the name suggests, i.e., it converts a string list to a BigInteger list, not the other way around.

Upvotes: 7

Dinal
Dinal

Reputation: 661

public static {ReturnType} {MethodName} ({Arguments})

This is how your method signature should be. Cannot understand why you are having <BigInteger> after static in method signature.

Upvotes: 1

Kasper Ziemianek
Kasper Ziemianek

Reputation: 1345

Your method signature has wrong syntax. You should remove <BigInteger> to make function return object of type List<BigInteger>

  public static List<BigInteger> convertIntegerListToStringList(List<String> existingList)
  {
      ArrayList<BigInteger> newList = new ArrayList<BigInteger>();
      for(String item : existingList) {
        newList.add(new BigInteger(item));
      }
    return newList;
  }

You also forgot about semicolon after return variable name.

Upvotes: 2

Related Questions