【问题标题】:getting floats rather than objects out of an Arraylist从 Arraylist 中获取浮点数而不是对象
【发布时间】:2011-12-11 16:45:27
【问题描述】:

我正在尝试创建一种从二维数组中删除重复项的方法。外部数组包含点索引,内部数组包含它们的坐标。看起来我必须使用 arraylist 才能删除元素,而不会在数组中得到空值。然后我想将数组列表转换回二维数组,以便以我需要的格式返回它。问题是 arraylsit 包含一个对象数组,所以我不能将它转换为为浮点数设计的数组。从我的数组列表中过滤浮点数的正确语法是什么。我的代码如下:

public class rem_duplicates {
    public float [][] rem_geo_duplicates(float a[][]){

        ArrayList<float[]> al = new ArrayList<float[]>();
        float no_points = a.length;
        int count = 0;


        for (int i = 0; i < no_points-1; i++){
            if((a[i][0] == a[i+1][0])&&(a[i][1] == a[i+1][1])){
                    a[i] = null;
                    count ++;
            }

        for (int j = 0; j < no_points; j++){
            if (a[j] != null){
                al.add(a[j]);       
            }
        }

        //how do i get the arraylist 'al' into this array b[][]?
        float b[][] = new float [a.length-count][3];
        b = al.toArray();


        }

    }
    return b
}

【问题讨论】:

    标签: java arrays arraylist indexing duplicates


    【解决方案1】:

    尝试使用以下方法:

    float b[][] = new float [a.length-count][3];
    b = al.toArray(b);
    

    这是toArray() 的通用版本,在您的情况下将返回float[][]。请记住,float[] 是一个对象,因此这里不存在装箱/拆箱问题。

    我注意到您的代码存在几个基本问​​题 - 我建议尝试编译它并解决错误。

    【讨论】:

      【解决方案2】:

      如果您将新创建的数组作为参数传递,它可以正常工作:

      float b[][] = new float[a.length-count][];
      b = al.toArray(b);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-08
        • 2020-03-28
        • 1970-01-01
        • 2019-03-15
        • 1970-01-01
        • 2015-04-18
        相关资源
        最近更新 更多