有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何一次访问拆分字符串的两个元素?

问题:我有一个字符串100, 200, boxes。我想把这个字符串转换成一个对象,比如说TreeMap<String, List>,其中100, 200是一个值列表boxes是一个键字符串。 结果应该像[100, 200]: "boxes"

稍后我想访问值:my_map.get("boxes")[0]my_map.get("boxes")[1]例如

我的解决方案:假设我有一个包含3列的文件,我读取数据,拆分数据,然后在每行上迭代,不断拆分该行。我想我有[100, 200, "boxes"]。现在,在python中,我可以通过提供一系列索引(如[0:1])来访问所需的元素

如何在Java中做同样的事情

for (String line : mydata.split("\n|\r\n")) {

            String[] sl = line.split(" |\t");
            String[] my_two_elements = sl[0:1]; <-- No way!

        } 

共 (1) 个答案

  1. # 1 楼答案

    您正在寻找^{}

    Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case null is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from.

    The resulting array is of exactly the same class as the original array.

    始终参考源代码了解实现细节,并分析代码的性能

    3035    public static <T,U> T[] More ...copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
    3036        int newLength = to - from;
    3037        if (newLength < 0)
    3038            throw new IllegalArgumentException(from + " > " + to);
    3039        T[] copy = ((Object)newType == (Object)Object[].class)
    3040            ? (T[]) new Object[newLength]
    3041            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    3042        System.arraycopy(original, from, copy, 0,
    3043                         Math.min(original.length - from, newLength));
    3044        return copy;
    3045    }