队列和栈的一些知识
1.stack的一些操作:
stack.push(x); 进栈,返回x
**stack.peek(); 获取栈顶元素,但不删除它
stack.pop(); 获取栈顶元素,并且删除它**
* If the object {@code o} occurs as an item in this stack, this
* method returns the distance from the top of the stack of the
* occurrence nearest the top of the stack; the topmost item on the
* stack is considered to be at distance {@code 1}
源码如下
* public synchronized int search(Object o) {
int i = lastIndexOf(o);
if (i >= 0) {
return size() - i;
}
return -1;
}
stack.search();获取某一位置的元素距离栈顶的距离,栈顶元素的距离看为1
2.String和int相互转换:
A.String变int:
1). int i = Integer.parseInt([String]); 或
i = Integer.parseInt([String],[int radix]);
2). int i = Integer.valueOf(my_str).intValue();
注: 字串转成 Double, Float, Long 的方法大同小异.
B.int变String:
1.) String s = String.valueOf(i);
2.) String s = Integer.toString(i);
3.) String s = "" + i;
注: Double, Float, Long 转成字串的方法大同小异.
3.比较字符串是否相同时的两种方法:
第一种方法:java中字符串的比较:==
我们经常习惯性的写上if(str1 == str2),这种写法在java中可能会带来问题
example1:
String a=“abc”; String b=“abc”
那么a == b将返回true。因为在java中字符串的值是不可改变的,相同的字符串在内存中只会存一份,所以a和b指向的是同一个对象;
example2:
String a=new String(“abc”); String b=new String(“abc”);
那么a==b将返回false,此时a和b指向不同的对象。
第二种方法:用equals方法比较的是字符串的内容是否相同,
example:
String a=new String(“abc”);
String b=new String(“abc”);
a.equals(b);
将返回true。 最好是用equals方法
4.int 与 integer的区别:
(1)、Integer是int的包装类,int则是java的一种基本数据类型
(2)、Integer变量必须实例化后才能使用,而int变量不需要
(3)、Integer实际是对象的引用,当new一个Integer时,实际上是生成一个指针指向此对象;而int则是直接存储数据值
(4)、Integer的默认值是null,int的默认值是0
5 .quene的操作
boolean add(E e);进队
boolean offer(E e);进队
区别:两者都是往队列尾部插入元素,不同的时候,当超出队列界限的时候,add()方法是抛出异常让你处理,而offer()方法是直接返回false
/**
* Retrieves and removes the head of this queue. This method differs
* from {@link #poll() poll()} only in that it throws an exception if
* this queue is empty.
*
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
/
E remove();
/*
* Retrieves and removes the head of this queue,
* or returns {@code null} if this queue is empty.
*
* @return the head of this queue, or {@code null} if this queue is empty
*/
E poll();
区别:两者都是移出并返回队首,但当队列为空时,remove抛出异常,poll直接饭后null。
/**
* Retrieves, but does not remove, the head of this queue. This method
* differs from {@link #peek peek} only in that it throws an exception
* if this queue is empty.
*
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
/
E element();
/*
* Retrieves, but does not remove, the head of this queue,
* or returns {@code null} if this queue is empty.
*
* @return the head of this queue, or {@code null} if this queue is empty
*/
E peek();
区别:两者都是返回队首但不移出,在队列为空时,element抛出异常,peek返回null。
ps: ctrl+T在eclipse中快速查看接口的实现类