在 ArrayList 中存储不同的类型 [英] Store different types in ArrayList

查看:58
本文介绍了在 ArrayList 中存储不同的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将元素存储在一个列表中,每个元素有 4 个参数我正在尝试创建一个数组列表,为每个元素存储 4 个不同类型的参数:

I want to store elements in a list, each elements having 4 parameters I'm trying to create an array list that stores for each element the 4 parameters , which are of different types:

ID:整数
x 位置:浮动
y 位置:浮动
名称:字符串

iD: int
x position : float
y position : float
name : string

我使用:

ArrayList<String> activList ;

但是当我使用:

 activList.add(2, 4.5, 8.9,"Name");

我收到错误:

" ArrayList 类型中的 add(int,Object) 方法不适用于参数 (in, float, float)"

" the method add(int,Object) in the type ArrayList is not applicable for the arguments (in, float, float)"

我不知道如何向 ArrayList 添加不同的类型,有没有办法做到这一点?

I don't know how to be able to add different types to an ArrayList, is there a way to do it ?

感谢您的帮助

推荐答案

您可能需要创建自己的类来表示这 4 个参数.然后您可以将该对象的实例插入到 ArrayList 中:

You probably need to create your own class to represent those 4 parameters. Then you can insert instances of that object into the ArrayList:

public class MyParameters {
    private int id;
    private float x;
    private float y;
    private String name;

    public MyParameters(int id, float x, float y, String name) {
        // ...
    }

    // + getters, setters
}

// ...

List<MyParameters> myParameters = new ArrayList<>();
myParameters.add(new MyParameters(2, 4.5, 8.9, "Name"));

这篇关于在 ArrayList 中存储不同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆