前段时间,在做一个商品的分类,分类有3级,类似于以下这种形式的:

  ---食物

    ---蔬菜

      ---白菜

    ---材料

      ---鸡肉

.......

  而我需要做的是将取得的一个商品的字符串类型的分类ID集,然后在前台显示其分类。显示的模式就像这样的:"口味:甜、酸;材料:鸡肉、牛肉..."。商品的分类是可能多选的,而且所选分类也不一定就是一个大分类里面的,所以就必须在取得分类集合后进行同类型分类。而根据同类型分类的依据就是该分类的最大父类与其他分类是相同的。在其获得的分类中,有一个getParent()方法可以获取父类对象,当不存在父类类型的时候,会取得空值。

  我首先想到的是把字符串ID集转换成分类集合是第一步。即String[] productCategories => List<ProductCategory>。这步很简单,不多说明。

  第二步,我最初的想法是,建立一个List<List<ProductCategory>>集合,这个集合里面存放分类集合,一个元素作为同一类型存放。先将转换好的List<ProductCategory>集合copy一份,然后用这两个集合两层循环嵌套比较,

  代码类似下面的这样的:
  

     List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
List<String> list2 = list;
List<List<String>> bigCate = new ArrayList<List<String>>();
for (String str : list) {
List<String> cate = new ArrayList<String>();
cate.add(str);
for (String str2 : list2) {
if(str.equals(str2)){
cate.add(str2);
list.remove(str2);
}
}
bigCate.add(cate);
}
System.out.println(bigCate);

这样就把相同分类比较出来了,然后存进List<List<ProductCategory>>集合中。可是并不是那么简单,其中有两个问题需要解决,也是我对java面向对象理解不深刻的地方。

  其一:java对象都是引用对象,java没有指针,并不是真的没有指针,而是被封装起来了,我们没有接触到而已。所以把集合copy一份,仅仅是把已经存在于stack中的指向存放集合数据的地址copy了一份。所以在执行remove方法时,实际上也移除了list2集合的元素。在行14的操作中我想在copy的集合中移除掉已经分类好的元素,结果报出java.util.ConcurrentModificationException异常。

  其二:java中List集合的安全机制。list集合在增加元素的时候,查看ArrayList的源码中,可以看到以下代码:

   public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}

而其中的ensureCapacity(size+1)方法是增加modcount变量值的。即以下代码:

  public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
}

  那么我在执行for-each循环的时候,又移除元素(实际上循环遍历与移除都是同一个对象),那么在remove(object)的时候,又是执行什么操作的呢,在源码中发现:

     public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}

  其实内部是先用普通for循环遍历,然后if判断找出元素索引,然后再执行fastRemove(index)。那我们再看看这个fastRemove(int index)方法是什么样的:

    private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
}

  我们发现它也执行了modCount++操作,那么在增加元素和移除元素的时候,这个modCount都在执行自增操作,那么到这里,你可能已经猜到一些原因了。我们继续查看源码,ArrayList执行for-each迭代时候,实际上是实现了一个Iterator接口的方法,iterator有几个方法,代码如下:

 public interface Iterator<E> {

     boolean hasNext();

     E next();

     void remove();
}

   那么在AbstractList中,它使用了一个内部类来实现Iterator:

 private class Itr implements Iterator<E> {
int cursor = 0; int lastRet = -1; int expectedModCount = modCount; public boolean hasNext() {
return cursor != size();
} public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
} public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification(); try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}

  它在内部定义了一个游标变量cursor,通过游标来获取集合元素并且判断集合是否还有下一个值,确定集合执行hasNext()方法之后还有数据,然后会执行next()方法取得下一个值。我们还观察到,在这个迭代器中第6行,它定义了一个变量int expectedModCount = modCount;那么从我刚才写的那个分类来看,在第二次for-each循环中,在list执行了remove方法之后,modCount已经等于5了。但是在一开始执行for-each迭代器已经将modCount变量赋值给expectedModCount了,那个时候集合还没有执行remove方法,此时modCount=4。那么在next()方法中它首先会调用一个checkForComodification()方法, checkForComodification()方法的代码如下:

  

 final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}

  看到没有,它会检查modCount是否等于expectedModCount,如果不相等,说明集合在迭代的时候结构发生了变化,然后抛出ConcurrentModificationException异常。

  整个过程就是这样的。也许看起来是比较简单的,但是我觉得了解java的一些原理和机制,学习一下它里面的数据结构也并不是什么坏事。

  本篇纯原创,转载请注明出处。最近经常用到集合,java为集合提供了很多简洁快捷的方法。所以没事就随意看了下java源码,如有不同见解,欢迎交流!谢谢!

  

最新文章

  1. HBase数据库集群配置
  2. Gradle版本变更的问题
  3. Rhythmbox中文乱码
  4. 解决Win10服务主机本地系统网络受限
  5. 按照需要分别率长宽比导出图片(python 3)
  6. Python--类定义
  7. Java Swing界面编程(1)
  8. Bootstrap新手常见问题
  9. Unity3d 要点板书
  10. iSwifting如何发送照片社区
  11. Java泛型类和泛型方法
  12. Python-函数-Day4
  13. 如何简单快速的修改Bootstrap
  14. P3244 [HNOI2015]落忆枫音
  15. python模块之HTMLParser解析出URL链接
  16. java远程下载文件到本地
  17. jeecms一些经典标签
  18. openAI最近推出了一个新的语言模型 &quot;GPT-2&quot;
  19. Atitit.&#160;&#160;单列索引与多列索引&#160;多个条件的查询原理与设计实现
  20. h5新特性--- 多媒体元素

热门文章

  1. jQuery仿苹果样式焦点图插件
  2. hdu1010感想
  3. nginx面试要点
  4. Email-Ext Plugin install ------ Jenkins Plugins
  5. Apache Phoenix的Array类型
  6. 2017 GDS 全球域名大会7月7日举行
  7. ios 获取导航栏和状态栏高度,针对iPhoneX
  8. Lucene.Net 优化索引生成,即搜索显示优化
  9. let和const命令新总结
  10. 《Advanced Bash-scripting Guide》学习(十):利用whois查询域名信息