201521123038 《Java程序设计》 第七周学习总结

201521123038 《Java程序设计》 第七周学习总结


1. 本周学习总结

2. 书面作业

1.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;
    }

  • equals:
    public boolean equals(Object obj) {
        return (this == obj);
    }
  • 由上段代码可以看出contains主要是通过indexof的返回值来确认有没有包含某个对象。indexof通过调用equals来比较对象的存储地址,从而返回对象的下标,当对象不存在时返回-1。当两个对象值相同但是存储地址不同的时候,会被视为两个不同的对象。所以当使用contains来确认有没有包含相同内容的对象时,最好重写equals。

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

  • remove
    public E remove(int index) {
        rangeCheck(index);
		//检测传入数据是否溢出

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

        int numMoved = size - index - 1;
		//numMoved:需要移动的元素个数



        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
		//将移除的元素后的每一个元素都往前移一位


        elementData[--size] = null; // clear to let GC do its work
		//将最后一位置为null

        return oldValue;
    }

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

  • 在没有声明ArrayList存取数据的类型的时候不需要考虑元素的类型,因为ArrayList源代码的初始数据类型都是Object。下图中的int类型会被自动转为Integer。

  • 在声明ArrayList存取数据的类型的时候不能使用基本数据类型,如:int,char,byte。

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

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;//添加对象时,将size加一
        return true;
    }


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

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;//储存结构修改次数

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);//超出容量是扩容
    }


    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);//新容量扩大到原容量的1.5倍,右移一位相当于原数值除以2。
        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倍

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


    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

由代码可以看出,如果index超出size范围,就会抛出异常。

rangeCheck被get(int index),set(int index, E element,remove(int index)调用,用remove(int index)作个例子:

    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来判断是否越界,那这就是内部判断的方法,不需要对外部可见,而外部判断是否越界可以通过对比size而不需要调用rangeCheck就可以实现,所以用private声明。将不需要被外部调用的方法声明为private,可以保证代码的安全性。

2.HashSet原理

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

    public HashSet() {
        map = new HashMap<>();
    }

HashSet实质上是用HashMap实现的。因为HashSet存储的对象都是不重复的,所以当HashSet储存元素时,调用了hashCode方法来确定储存位置。如果位置相同,则再通过调用equals来确定内容是否相同。

3.ArrayListIntegerStack

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

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

(这两道题我都是用ArrayList实现的。。)
一开始就用ArrayList来实现栈是因为考虑到如果用单纯的数组实现,就要考虑数组大小,虽然题目给定数组大小,但是ArrayList使用起来更方便:

  • 用简单的数组Array实现栈要考虑栈顶指针的移动,并且一开始就要给定数组大小。

  • 用ArrayList实现栈在实现添加删除操作的时候便捷的方式可以直接采用,不需要使用栈顶指针,因为ArrayList是动态数组,可以自动扩容,所以不用考虑大小的问题。

3.2 简单描述接口的好处.

  • 定义一个接口,则实现这个接口的类必须实现接口中的方法
  • 不同的方法可以有不同的实现方式,上层代码只需要调用接口中的方法不需要考虑方法的具体实现

4.Stack and Queue

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


import java.util.ArrayList;
import java.util.Scanner;

interface StringStack{
	public String push(String string);
	public String pop(); 
}
class MyStack implements StringStack
{
	private ArrayList<String> list=new ArrayList<String>(); 
	
	public MyStack() {
		list=new ArrayList<String>();
	}

	@Override
	public String push(String item)
	{
		if(item==null) return null;	
		list.add(item);
		return item;
	}
	@Override
	public String pop()
	{
		if(!list.isEmpty())
		{
			return list.remove(list.size()-1);
		}
		return null;
	}
}

public class Main201521123038 {
	public static void main(String[] args) {
		Scanner input=new Scanner(System.in);
		String s=input.next();
		int i;
		StringStack stack=new MyStack();
		for(i=0;i<s.length();i++)
			stack.push(String.valueOf(s.charAt(i)));
		for(i=0;i<s.length();i++)
		{
			if(String.valueOf(s.charAt(i)).equals(stack.pop()))continue;
			else
			{
				System.out.println("false");
				break;
			}
		}
		if(i==s.length()) System.out.println("true");
		

	}

}

  • 这个栈和之前的ArrayIntegerStack相似,只需要在原来的代码上面稍作修改,顺便删除一部分不需要的代码。但是现在编写的是String类型的栈,和Integer类型的还是有一些不同。在作对比的时候要将字符串中提取出的字符转换为字符串,用String.valuesof()。

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

  • 编号按奇偶数分流:
		for(int i=0;i<size;i++)
		{
			num=input.nextInt();
			if(num%2==0) qb.offer(num);
			else qa.offer(num);
		}

  • 处理顺序:
		for(int i=0;i<size;)
		{
			if(!qa.isEmpty()&&i<size) 
			{
					q.offer(qa.poll());
					i++;
			}
			if(!qa.isEmpty()&&i<size)
			{
				q.offer(qa.poll());
				i++;
			}
			if(!qb.isEmpty()&&i<size)
			{
				q.offer(qb.poll());
				i++;
			}
		}

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

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

		TreeSet<String>words=new TreeSet<String>();
		String s;
		while(input.hasNext())
		{
			s=input.next();
			if(s.equals("!!!!!"))
				break;
			words.add(s);
		}
		System.out.println(words.size());
		int i=0;
		for(String e:words)
		{
			if(i==10) break;
			System.out.println(e);
			i++;
		}

5.1 实验总结

  • 刚开始做的时候有考虑用HashMap,但是题目只要求按字母顺序输出,用TreeSet可以直接进行排序。HashMap更适用于下一题那样要求多的排序。
  • 用hasNext()来判断是否有继续输入在这道题里面比用splits要来的方便。

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

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

6.1 伪代码

		Map<String,Integer>words=new HashMap<String,Integer>();
		
		while(input.hasNext())
		{
			int count=1;
			s=input.next();
			if(s.equals("!!!!!"))
				break;
			if(words.containsKey(s)) count=words.get(s)+1;
			words.put(s, count);
		}

		... ...

		List<Entry<String,Integer>> list =new ArrayList<Entry<String,Integer>>(words.entrySet());

		Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
			//按次数排序	
		});
	
		Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
			//次数相同按字母排序
		});
		
		System.out.print()//按要求输出

6.2 实验总结

  • 用Collections.sort和匿名类对内容进行排序,本来想一次性解决,但操作的时候排序会出错,所以分两次排序来解决。

  • 中途要把HashMap转为List,才能调用Collections进行排序。

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

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

  • 增加了购物车界面,两个界面之间的转换正在完善

7.2 使用集合类改进大作业

  • ShoppingCart列表用list实现

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

3.1. 码云代码提交记录

原文地址:https://www.cnblogs.com/sakurai3104/p/6681924.html