201521123081《java程序设计》 第7周学习总结

1. 本周学习总结

以你喜欢的方式(思维导图或其他)归纳总结集合相关内容。

参考资料:XMind

2. 书面作业

Q1. ArrayList代码分析

1.1 解释ArrayList的 contains 源代码

//粘贴源代码
//contains()方法
public boolean contains(Object o) {
    return indexOf(o) >= 0;
  }  
//indexOf()方法
public int indexOf(Object o) {
    if (o == null) {
        for (int i = 0; i < size; i++)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}  
  • 由代码可知,如果对象不为null的话,最终是调用的Object类的 equals() 方法,来比较两个对象的引用是否相同。

  • 若列表包含指定元素,则返回true。

1.2 解释 E remove(int index) 源代码

//粘贴源代码
//remove()方法
public E remove(int index) {
  rangeCheck(index);

  modCount++;
  E oldValue = elementData(index);

  int numMoved = size - index - 1;
  if (numMoved > 0)
      System.arraycopy(elementData, index+1, elementData, index,
                       numMoved);
  elementData[--size] = null; // clear to let GC do its work

  return oldValue;
}
//rangeCheck()方法
private void rangeCheck(int index) {
  if (index >= size)
      throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

首先判断要删除的位置,如果超出List大小,就会抛出 IndexOutOfBoundsException 异常;删除此列表中指定位置的元素;删除某个元素后,在这个位置之后的元素全部往前移,最后再把size-1的位置赋为null。

1.3 结合1.1与1.2,回答ArrayList存储数据时需要考虑元素的类型吗?

不用考虑,因为参数是Objcet类型的对象,Object类又是所有类父类,只要不是基本数据类型都行。

1.4 分析add源代码,回答当内部数组容量不够时,怎么办?

public boolean add(E e) {
    ensureCapacityInternal(size + 1);//确保内部的容量空间足够
    elementData[size++] = e;//变为所需的容量空间
    return true;
}

private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }

    ensureExplicitCapacity(minCapacity);
}
    modCount++;
    // overflow-conscious code
    if (minCapacity - elementData.length > 0) //如果超出容量空间大小
        grow(minCapacity);//调用grow方法增加容量空间
}

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);//扩容,增加原来容量的一半,即扩大到原来的1.5倍
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity); //创建一个新数组来存放原来的数据
}

1.5 分析 private void rangeCheck(int index) 源代码,为什么该方法应该声明为private而不声明为public?

  • 内部方法,rangeCheck用于边界检查,在类内调用就可以了。
  • 用户在使用ArrayList的方法时不需要考虑是否越界的问题,因为这个问题在方法内部已经解决了。

Q2. HashSet原理

2.1 将元素加入HashSet(散列集)中,其存储位置如何确定?需要调用那些方法?

  • 首先计算出待存储元素的散列码,作为存储的位置的依据,找到对应下标,若发生冲突,则放在发生冲突的元素的后面,用链表连接。
  • hashCode() 方法和 equals() 方法。
    ①. 调用该对象的hashCode()方法得到其hashCode值,作为存储的位置的依据;
    ②. 若已存在其它元素,则调用加入元素的equals()方法与已有元素进行比较。根据比较结果,找到位置。

2.2 选做:尝试分析HashSet源代码后,重新解释1.1

Q3. ArrayListIntegerStack

题集 jmu-Java-05-集合 之5-1 ArrayListIntegerStack

3.1 比较自己写的ArrayListIntegerStack与自己在题集 jmu-Java-04-面向对象2-进阶-多态、接口与内部类 中的题目5-3 自定义接口ArrayIntegerStack ,有什么不同?(不要出现大段代码)

  • 两者实现的是同一个接口,所以方法作用都基本相同。
  • 存储方式不同,前者使用ArrayList,后者使用Integer数组。ArrayListIntegerStack不需要考虑数组的大小,能够自动扩容,而ArrayIntegerStack在实例化时要规定大小。
  • ArrayIntegerStack需要 top 指针确定出入栈,判断栈顶元素,而ArrayListIntegerStack只需要调用已有的方法就可以了。

3.2 简单描述接口的好处.

这是接口的定义,我们已知方法,可以用不同的方式来实现它。根据不同情况需求,可以使用不同的方式来实现,灵活性很高。

Q4. Stack and Queue

4.1 编写函数判断一个给定字符串是否是回文,一定要使用栈,但不能使用java的 Stack 类(具体原因自己搜索)。请粘贴你的代码,类名为 Main你的学号

package 博客园作业暂存;

import java.util.LinkedList;
import java.util.Scanner;

class Stack<T> {
    private LinkedList<T> list = new LinkedList<T>();
    public void push(T v) {
        list.addFirst(v);
    }
    public T pop() {
        return list.removeFirst();
    }
}

public class Main201521123081 {
    public static void main(String[] args) {
        Stack<Character> stack = new Stack<Character>();
      System.out.println("请输入字符串:");
		@SuppressWarnings("resource")
		Scanner sc=new Scanner(System.in);
        String s1=sc.next();
        for (int i = 0; i < s1.length(); i++) {
            stack.push(s1.charAt(i));
        }
        boolean judge = true;
        for (int i = 0; i < s1.length(); i++) {
            if (stack.pop() != s1.charAt(i)) {
                judge = false;
                break;
            }
        }
        
        if (judge) {
            System.out.println("是回文!");
        } else {
            System.out.println("不是回文!");
        }
    }
}

4.2 题集jmu-Java-05-集合 之5-6 银行业务队列简单模拟。(不要出现大段代码)

for (int i = 0; i < n; i++) {
	if(q1.size()==2){
	System.out.printf(q1.poll()+" "+q1.poll()+" ");
	if(q2.size()>=1)
	System.out.printf(q2.poll()+" ");
	}
	if(Num[i]%2==1)
		q1.add(Num[i]);
	else
		q2.add(Num[i]);
}
while(q1.size()>1){
	System.out.printf(q1.poll()+" ");
if(q1.size()==1)
	System.out.printf(q1.poll()+"");
while(q2.size()>1)
	System.out.printf(q2.poll()+" ");
if(q2.size()==1)
	System.out.printf(q2.poll()+"");
in.close();
}


按照题目要求,队列A出两个,队列B出一个。如果其中一个队伍为空,就将另一个队伍全部出列。

Q5. 统计文字中的单词数量并按单词的字母顺序排序后输出

题集jmu-Java-05-集合 之5-2 统计文字中的单词数量并按单词的字母顺序排序后输出 (不要出现大段代码)

5.1 实验总结

while(sc.hasNext()){
			String str=sc.next();
			if(str.equals("!!!!!")){
				break;
			}
			set.add(str);
		}
		System.out.println(set.size());
		int i=0;
		for (Iterator<String> iterator = set.iterator(); iterator.hasNext()&&i<10;) {
			i++;
			String string = (String) iterator.next();
			System.out.println(string);
		}

  • 统计文本出现的词汇并存储,使用Set来存储,但HashSet只是无重复的存储单词,没有排序。此时需要用TreeSet,TreeSet会在内部帮我们排序好。
  • 要特别注意空格的存在。

Q6. 选做:加分考察-统计文字中的单词数量并按出现次数排序

题集 jmu-Java-05-集合 之5-3 统计文字中的单词数量并按出现次数排序(不要出现大段代码)

while (in.hasNext()) {
	String str = in.next();
	if (str.equals("!!!!!"))
		break;
	else if (!num.containsKey(str))
		num.put(str, 1);
	else {
              int n = (int) num.get(str);
	      num.put(str, n + 1);
              }
	}		
System.out.println(num.size());
List<Map.Entry<String, Integer>> arrayList = new ArrayList<Map.Entry<String, Integer>>(num.entrySet());
Collections.sort(arrayList, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
	return ((Integer) o2.getValue()) - ((Integer) o1.getValue());
	}
});
		
int n=10;
for (Map.Entry<String, Integer> entry : arrayList) {
	if(n--==0)
		break;
	String key = entry.getKey();
	Integer value = entry.getValue();
	System.out.println(key + "=" + value);

6.1 伪代码

while(has next input)
    if( map doesn't contain next num )
        put num into map
    else
        get the value in map to add 1
sort the map
output the result

6.2 实验总结

把Map当中的元素放在ArrayList当中,然后用Collections.sort()方法对ArrayList进行排序。

面向对象设计大作业-改进

7.1 完善图形界面(说明与上次作业相比增加与修改了些什么)

7.2 使用集合类改进大作业

参考资料:

JTable参考项目

3. 码云上代码提交记录及PTA实验总结

题目集:jmu-Java-05-集合

3.1. 码云代码提交记录

  • 在码云的项目中,依次选择“统计-Commits历史-设置时间段”, 然后搜索并截图

3.2. PTA实验

  • 编程(5-1, 5-2, 5-3(选做), 5-6)
  • 实验总结已经在作业中体现,不用写。
posted @ 2017-04-08 19:08  圆滑鞘翅  阅读(177)  评论(0编辑  收藏  举报