Java字符串和BigInteger之间的转换

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

在上一个教程中,我们看到了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)-将提供的字符串转换为特定转换器定义的对象。

package net.javaguides.string.conversion;

/**
* Converter defines conversion behavior between strings and objects.
* The type of objects and formats of strings are defined by the subclasses
* of Converter.
*/
public interface StringConverter<T> {
    /**
* Converts the object provided into its string form.
* @return a string representation of the object passed in.
*/
    public abstract String toString(T object);

    /**
* Converts the string provided into an object defined by the specific converter.
* @return an object representation of the string passed in.
*/
    public abstract T fromString(String string);
}

BigIntegerStringConverter.java

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

package net.javaguides.string.conversion;

import java.math.BigInteger;

/**
* <p>
* {@link StringConverter} implementation for {@link BigInteger} values.
* </p>
*/
public class BigIntegerStringConverter implements StringConverter < BigInteger > {
    @Override
    public BigInteger fromString(String value) {
        // If the specified value is null or zero-length, return null
        if (value == null) {
            return null;
        }

        value = value.trim();

        if (value.length() < 1) {
            return null;
        }

        return new BigInteger(value);
    }

    @Override
    public String toString(BigInteger value) {
        // If the specified value is null, return a zero-length String
        if (value == null) {
            return "";
        }

        return ((BigInteger) value).toString();
    }

    public static void main(String[] args) {

        String string = "100";
        BigIntegerStringConverter bigIntegerStringConverter = new BigIntegerStringConverter();
        BigInteger bigInteger = bigIntegerStringConverter.fromString(string);
        System.out.println("String to bigInteger -> " + bigInteger);

        String bigIntstr = bigIntegerStringConverter.toString(bigInteger);
        System.out.println("bigInteger to string -> " + bigIntstr);

    }
}

输出:

String to bigInteger -> 100
bigInteger to string -> 100

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

相关文章

微信公众号

最新文章

更多