有 Java 编程相关的问题?

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

java从Arraylist中获取浮点数而不是对象

我试图创建一种方法,从2d数组中删除重复项。外部数组包含点索引,内部数组包含它们的坐标。看起来我必须使用arraylist才能删除元素,而不会在数组中出现空值。然后我想将arraylist转换回2D数组,以便以我需要的格式返回它。问题是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
}

共 (2) 个答案

  1. # 1 楼答案

    如果将新创建的数组作为参数传递,则效果良好:

    float b[][] = new float[a.length-count][];
    b = al.toArray(b);
    
  2. # 2 楼答案

    尝试使用以下方法:

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

    这是^{}的通用版本,在您的情况下,它将返回一个float[][]。请记住float[]是一个对象,因此这里没有装箱/拆箱的问题

    然而,我注意到你的代码有几个基本问题——我建议尝试编译它并解决错误