简体   繁体   中英

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.

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, ie, it converts a string list to a BigInteger list, not the other way around.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM