代码之家  ›  专栏  ›  技术社区  ›  nikolouzos

如果我想设置数组的大小,并且我想在空点中设置null,那么我应该使用什么类型的数组

  •  1
  • nikolouzos  · 技术社区  · 7 年前

    我想使用一种具有设置大小的数组类型(因此我需要自己设置大小),但我不想丢弃数组中的空白点,我只希望它们为null。 基本上我有一个适配器,可以用图片和文本填充ListView。我使用两个字符串数组获取文本和图片链接( 碎片 ):

    String[] itemNames = getResources().getStringArray(R.array.catItems);
    String[] itemLinks =  getResources().getStringArray(R.array.catLinks);
    
    mMenuItems = findViewById(R.id.menuItems);
    mMenuItems.setAdapter(new MenuCatAdapter(this, itemLinks, itemNames));
    

    我想将itemLinks数组的长度设置为与itemNames数组相同。在MenuAdapter中,我在getView()方法中使用以下代码来设置ListView的文本和图像( 碎片 ):

    public View getView(int position, View convertView, ViewGroup parent) {
        View customView = convertView;
        LayoutInflater layoutInflater;
        ViewHolder holder = new ViewHolder();
    
        if(customView == null) {
            layoutInflater = LayoutInflater.from(mActivity.getApplicationContext());
            customView = layoutInflater.inflate(R.layout.nav_cat_list_item, parent, false);
    
            holder.itemImage = customView.findViewById(R.id.navCatImageView);
            holder.itemName = customView.findViewById(R.id.navCatTextView);
    
            customView.setTag(holder);
        }  else {
            holder = (ViewHolder) customView.getTag();
        }
    
        // Set the image
        if(mImageLinks[position] == null) { //What to do if the link is non-existent
            Glide   .with(mActivity.getApplicationContext())
                    .load(R.drawable.sidebar_sandwich)
                    .into(holder.itemImage);
        } else {
            Glide   .with(mActivity.getApplicationContext())
                    .load(mImageLinks[position])
                    .into(holder.itemImage);
        }
        holder.itemImage.setContentDescription(mItemNames[position]);
        // Set the text
        holder.itemName.setText(mItemNames[position]);
    
        return customView;
    }
    

    我想确保即使我没有图像的链接(因此链接为空),我仍然会得到占位符图像(或没有图像),而不是ArrayOutOfBoundsException。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Elliott Frisch    7 年前

    我想使用一种具有设置大小的数组类型(因此我需要自己设置大小),但我不想丢弃数组中的空白点,我只希望它们为null。

    每个Java数组都有一个固定的长度,必须在声明时提供。此外,如果它是引用类型的数组,则默认值 null 。所以

    String[] arr = new String[1];
    

    创建一个有足够空间存储单个 String 。默认值为 无效的 ,因此

    System.out.println(arr[0]);
    

    输出

    null