Java字符串和BigInteger之间的转换

x33g5p2x  于2022-10-16 转载在 Java  
字(2.2k)|赞(0)|评价(0)|浏览(2749)

在上一个教程中,我们看到了BigDecimal和String之间的转换。在本教程中,我们将学习如何将String转换为BigInteger,还将BigInterger转换回String。

在本教程中,我们使用两个泛型方法创建StringConverter<>泛型接口。此接口可用于将任何包装类(Integer、Short、Double等)转换为String,反之亦然。

*toString(T object)-将提供的对象转换为字符串形式
*T fromString(String str)-将提供的字符串转换为特定转换器定义的对象。

StringConverter.java

这里我们创建一个通用的StringConverter<>接口。此接口声明以下泛型方法

*toString(T object)-将提供的对象转换为字符串形式
*T fromString(String str)-将提供的字符串转换为特定转换器定义的对象。

  1. package net.javaguides.string.conversion;
  2. /**
  3. * Converter defines conversion behavior between strings and objects.
  4. * The type of objects and formats of strings are defined by the subclasses
  5. * of Converter.
  6. */
  7. public interface StringConverter<T> {
  8. /**
  9. * Converts the object provided into its string form.
  10. * @return a string representation of the object passed in.
  11. */
  12. public abstract String toString(T object);
  13. /**
  14. * Converts the string provided into an object defined by the specific converter.
  15. * @return an object representation of the string passed in.
  16. */
  17. public abstract T fromString(String string);
  18. }

BigIntegerStringConverter.java

让我们创建一个BigIntegerStringConverter类,它将String转换为BigIntger,并且我们还将BigInterger转换回String。

  1. package net.javaguides.string.conversion;
  2. import java.math.BigInteger;
  3. /**
  4. * <p>
  5. * {@link StringConverter} implementation for {@link BigInteger} values.
  6. * </p>
  7. */
  8. public class BigIntegerStringConverter implements StringConverter < BigInteger > {
  9. @Override
  10. public BigInteger fromString(String value) {
  11. // If the specified value is null or zero-length, return null
  12. if (value == null) {
  13. return null;
  14. }
  15. value = value.trim();
  16. if (value.length() < 1) {
  17. return null;
  18. }
  19. return new BigInteger(value);
  20. }
  21. @Override
  22. public String toString(BigInteger value) {
  23. // If the specified value is null, return a zero-length String
  24. if (value == null) {
  25. return "";
  26. }
  27. return ((BigInteger) value).toString();
  28. }
  29. public static void main(String[] args) {
  30. String string = "100";
  31. BigIntegerStringConverter bigIntegerStringConverter = new BigIntegerStringConverter();
  32. BigInteger bigInteger = bigIntegerStringConverter.fromString(string);
  33. System.out.println("String to bigInteger -> " + bigInteger);
  34. String bigIntstr = bigIntegerStringConverter.toString(bigInteger);
  35. System.out.println("bigInteger to string -> " + bigIntstr);
  36. }
  37. }

输出:

  1. String to bigInteger -> 100
  2. bigInteger to string -> 100

您可以在项目中直接使用StringConverterBigIntegerStringConverter

相关文章

最新文章

更多