Paparazzi

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. 本周学习总结#

2. 书面作业#

Q1 ArrayList代码分析##

1.1 解释ArrayList的contains源代码###

先看看contains的源代码:

 public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
    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;
    }

ArrayList的contains方法返回的是布尔型。传入的参数是object型,从indexOf中可以看到如果传入的是null因为null调用equals会报错。所以如果找到了,就直接返回,找不到跳出循环外面,就返回-1,标记为没找到,那么contains()方法也会直接返回false。

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));
}
rangeCheck中先判断传入的数值是否越界,如果越界则报错。如果没有越界,则将对应下标的元素取出来,然后下标之后的元素全部往前一位,最后一位变为NULL,size再减一然后返回被删除的元素。

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

ArrayList中的方法中参数的类型都是Object类,Object类又是所有类的父类,所以不需要考虑元素的类型。

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

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    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);
    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);
}

private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}
首先要确保内部容量是size + 1。如果elementData是默认长度的空数组的话,那么就确保数组容量是传入参数和默认长度的最大值,也就是说这边至少开大小为10的数组。modCount自增。如果需要的容量比现有数组长度要大的话,就调用grow()方法。最后扩容然后确定了新的容量,使用Arrays.copyOf()方法来生成新的数组,将原来的数据拷贝到新数组中去。

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

private void rangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
因为用户并不用知道remov操作到底发生了什么,确保java的封装性。

Q2 HashSet原理##

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

答:HashSet的特点:元素排列没有顺序为基本操作提供常数时间性能--o(1)、没有提供同步机制(不适合用于多线程环境)、后台使用HashMap实现、加入HashSet中的类应该覆写equals()与hashCode(),保证这两个方法返回的结果一致。可以这样定义Set<> set = new HashSet<>();

Q3 ArrayListIntegerStack##

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

  • ArrayListIntegerStack是用ArrayList来实现栈,ArrayIntegerStack是用Integer数组来实现栈。
  • ArrayIntegerStack容量有限会出现栈满的情况,ArrayListIntegerStack不存在栈满的情况。
  • ArrayIntegerStack需要定义一个Top来入栈出栈,而ArrayListIntegerStack则不需要,直接用里面已有的方法就能实现入栈出栈。

3.2 简单描述接口的好处.###

ArrayIntegerStack,,ArrayListIntegerStack都实现了IntegerStack接口。这样做的好处就是我可以使用一个接口来操作不同的类,使用相同的方法。接口可以为以后程序的扩展性提供基础。一定程度保证了代码的安全性。让代码看起来简单规范。如果一个项目比较庞大,那么就需要一个能理清所有业务的架构师来定义一些主要的接口,这些接口不仅告诉开发人员你需要实现那些业务,而且也将命名规范限制住了(防止一些开发人员随便命名导致别的程序员无法看明白)。

Q4 Stack and Queue##

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

import java.util.LinkedList;

public class Main201521123014 {
	public static void main(String[] args) {
		Stack<Character> stack = new Stack<Character>();
		String str = "12321";
		// String str = "123456";

		for (int i = 0; i < str.length(); i++) {
			stack.push(str.charAt(i));
		}
		boolean flag = true;
		for (int i = 0; i < str.length(); i++) {
			if (stack.pop() != str.charAt(i)) {
				flag = false;
				break;
			}
		}

		if (flag) {
			System.out.println("yes");
		} else {
			System.out.println("no");
		}
	}
}

class Stack<E> {
	private LinkedList<E> stack = new LinkedList<E>();

	public void push(E o) {
		stack.addFirst(o);
	}

	public E peek() {
		return stack.getFirst();
	}

	public E pop() {
		return stack.removeFirst();
	}

	public boolean empty() {
		return stack.isEmpty();
	}

	public String toString() {
		return stack.toString();
	}
}

将字符串全部入栈,再一个个出栈与原字符串比较,如果没有出现不同的,就是回文串,否则不是。如果是空串,也是返回yes。

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

Queue<Integer> A=new LinkedList<Integer>();
Queue<Integer> B=new LinkedList<Integer>();

定义两个窗口。

for(i=0;i<n;i++){
    x=sc.nextInt();
    if(x%2==1) A.add(x);//奇数A窗口
    else B.add(x);//偶数B窗口
}

入队

while (!A.isEmpty() && !B.isEmpty()) {

			System.out.print(A.poll() + " ");
			if (!A.isEmpty()) {
				System.out.print(A.poll() + " ");
			}
			System.out.print(B.poll() + " ");
		}

		while (!A.isEmpty()&&B.isEmpty())

		{
			if(A.size()==1)
			System.out.print(A.poll());
			else System.out.print(A.poll()+" ");
		}
		while (A.isEmpty()&&!B.isEmpty()) {
			if(B.size()==1)
				System.out.print(B.poll());
				else System.out.print(B.poll()+" ");
		}

当两队不为空时 A出两次队,B出一次。然后再将非空的队全部输出。PTA上答案正确。

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

5.1 实验总结###

		Set<String> str = new TreeSet<String>();
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			String s = sc.next();
			if (!s.equals("!!!!!"))
				str.add(s);
			else
				break;
		}
		System.out.println(str.size());
		for (int i = 0; i < 10; i++) {
			System.out.println(str.toArray()[i]);
		}

使用 TreeSet,它具有自动排序功能。题目只要求10个单词 所以最好要加上str.toArray()[i];PTA提交正确。

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

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

使用了JTable使用起来更方便。(还未完成。)


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

3.2 PTA实验##

编程(5-1, 5-2, 5-3(选做), 5-6)
实验总结已经在作业中体现,不用写。

posted on 2017-04-08 16:56  Paparazzi  阅读(213)  评论(1编辑  收藏  举报