且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Arraylist 自定义位置

更新时间:2022-11-18 20:15:34

正如@itachiuchiha 提到的,你应该使用 Map.您提到的自定义数字"是您的 (整数),而值是 Random 对象.

As @itachiuchiha mentions, you should use a Map. The "custom numbers" you mention are your key (integers), and the value is the Random object.

顺便说一句,为了回应您的评论,下面是一个使用 Map 作为底层数据源的 Android Adapter 示例.

As an aside, in response to your comment, below is an example of an Android Adapter that uses a Map as the underlying datasource.

public class RandomsAdapter extends BaseAdapter {

    private Map<Integer, Random> randoms;

    public RandomsAdapter(Map<Integer, Random> randoms) {
        this.randoms = randoms;
    }

    public void updateRandoms(Map<Integer, Random> randoms) {
        this.randoms = randoms;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return randoms.size();
    }

    @Override
    public Random getItem(int position) {
        return randoms.get(position);
    }

    @Override
    public long getItemId(int position) {
        // we won't support stable IDs for this example
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = createNewView();
        }
        update(view, songs.get(position));
        return view;
    }

    private View createNewView() {
        // TODO: create a new instance of your view and return it
        return null;
    }

    private void update(View view, Random random) {
        // TODO: update the rest of the view
    }

}

注意 updateRandoms(Map randoms) 方法.

虽然您可以在适配器中公开一个方法来更新映射中的单个条目,但适配器不应该负责处理对映射的修改.我更喜欢再次传递整个地图——它仍然可以是对同一个对象的引用,但适配器不知道或不关心;它只知道:我的底层数据源已更改/修改,我需要告诉我的观察者他们应该通过调用 notifyDataSetChanged() 来刷新他们的视图".

While you could expose a method in the adapter to update a single entry in the Map, it shouldn't be the responsibility of the Adapter to handle modifications to the map. I prefer passing the entire map again - it could still be a reference to the same object, but the Adapter doesn't know or care; it just knows: "my underlying datasource has been changed/modified, I need to tell my observers that they should refresh their views by calling notifyDataSetChanged()".

或者,您可以在修改底层 Map 时在外部调用适配器上的 notifyDataSetChanged()(这会告诉 ListView 其数据已过期并再次从适配器请求其视图).

Alternatively, you could call notifyDataSetChanged() on the adapter externally when you modify the underlying Map (this tells the ListView that its data is out of date and to request its views from the adapter again).