黑马程序员技术交流社区
标题:
[邱烙考黑马]代码整理
[打印本页]
作者:
小爷邱烙
时间:
2014-11-27 19:34
标题:
[邱烙考黑马]代码整理
整理下代码,用于后面翻看
//if练习:把数字转成星期
int num = 2;
if(num==1)
System.out.println("Monday");
else if(num==2)//此处如果用if,则是多条语句,多次操作,效率低
System.out.println("Tuesday");
//...
else
System.out.println("error");
复制代码
作者:
小爷邱烙
时间:
2014-11-27 19:36
int month = 4;
if(month>12 || month<1)//先验证数据的正确性
System.out.println("error");
else if(month>=3 && month<=5)
System.out.println("春季");
//...
else
System.out.println("冬季");
复制代码
作者:
小爷邱烙
时间:
2014-11-27 19:39
switch语句
switch(表达式){
case 取值1:
执行语句;
break;
...
default:
执行语句;
break;//最后一个为default时,break可以省略不写
}
复制代码
作者:
小爷邱烙
时间:
2014-11-27 19:41
//switch练习:数字转季节
int month = 4;
switch(month){
case 3: //小技巧,当case不带执行语句且不break时,继续执行下一个case,适合区间条件
case 4:
case 5:
System.out.println("春季");
break;
//...
default:
System.out.println("error");
}
复制代码
作者:
小爷邱烙
时间:
2014-11-27 19:45
循环练习:获取1-10的和(重复执行加,使用累加思想)累加思想可用于加、减以及字符串操作
int sum = 0;//和始终变化,定义变量存储
int x = 1;//被加数也在变化,定义变量存储
while(x<=10){
sum = sum + x;
x++;
}
复制代码
作者:
小爷邱烙
时间:
2014-11-27 19:47
//由于x相加后无意义,用for更合适
int sum = 0;
for(int x=0;x<=10;x++){
sum +=x;
}
复制代码
作者:
小爷邱烙
时间:
2014-11-27 19:48
循环练习:计算1-100之间7的倍数的个数,并打印
int count = 0;
for(int x=0;x<=100;x++){
if(x%7==0)
count++;
System.out.println("count="+count);
}
复制代码
作者:
孟育俊
时间:
2014-11-27 19:50
学习啦!!!!
作者:
小爷邱烙
时间:
2014-11-27 19:51
循环嵌套练习:打印倒三角形
***** int z = 5;
**** for(int x=0;x<5;x++){//控制固定的行数
*** for(int y=0;y<z;y++){//控制递减的列数
** System.out.print("*");
* }
System.out.println();//换行
z--;//列数递减
}
//另一种形式
int z = 0;
for(int x=0;x<5;x++){
for(int y=z;y<5;y++){
System.out.print("*");
}
System.out.println();
z++;
}
//优化:z的变化规律与x相同
for(int x=0;x<5;x++){
for(int y=x;y<5;y++){
System.out.print("*");
}
System.out.println();
}
复制代码
作者:
小爷邱烙
时间:
2014-11-27 19:57
循环练习:打印正向三角形
* for(int x=0;x<5;x++){
** for(int y=0;y<=x;y++){
*** System.out.print("*");
**** }
***** System.out.println();
}
复制代码
作者:
小爷邱烙
时间:
2014-11-27 19:59
循环练习:打印数字三角形
1 for(int x=1;x<=5;x++){
12 for(int y=1;y<=x;y++){
123 System.out.print(y);
1234 }
12345 System.out.println();
}
复制代码
作者:
小爷邱烙
时间:
2014-11-27 20:00
循环练习:打印九九乘法表
for(int x=1;x<=3;x++){
for(int y=1;y<=x;y++){
System.out.print(y+"*"+x+"="+y*x+"\t");
}
System.out.println();
}
复制代码
作者:
小爷邱烙
时间:
2014-11-27 20:04
嵌套循环练习:打印等边三角形
* ----*
* * ---**
* * * -----> --***
* * * * -****
* * * * * *****
思路:先转成两个三角形组成的正方形,用空格替换-,用*加空格替换*
for(int x=0;x<5;x++){//控制列数
for(int y=x+1;y<5;y++){
System.out.print(" ");
}
for(int z=0;z<=x;z++){
System.out.print("* ");
}
System.out.println();
}
复制代码
作者:
小爷邱烙
时间:
2014-11-27 20:11
数组练习:取最值(使用遍历思想)
int x = arr[0];
for(int i=0;i<arr.length;i++){
if(x<arr[i])
x = arr[i];
}
System.out.println(x);
复制代码
作者:
小爷邱烙
时间:
2014-11-27 20:12
使用角标技巧取最值
int x = 0;//x为角标
for(int i=1;i<arr.length;i++){
if(arr[x]<arr[i])
x = i;
}
System.out.println(arr[x]);
复制代码
作者:
小爷邱烙
时间:
2014-11-27 20:13
数组排序(选择排序):先确定最小值,放在0角标,再一次确定各个角标的值
for(int i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i]>arr[j]){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}//由于数组是引用数据类型,交换完位置就是在堆内存中排好序了,所以不用返回值
复制代码
作者:
小爷邱烙
时间:
2014-11-27 20:14
数组排序(冒泡排序):相邻的两个元素比较,若前面的大于后面的,互换位置,先确定最大值的位置
for(int i=0;i<arr.length-1;i++){//外层控制圈数,最后一个元素无需比较
for(int j=0;j<arr.length-i-1;j++){//内层长度由外层控制,已经比较过的从长度中减去
if(arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
复制代码
作者:
小爷邱烙
时间:
2014-11-27 20:15
排序细节:抽取交换位置功能
public static void swap(int[] arr,int i,int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
复制代码
作者:
小爷邱烙
时间:
2014-11-27 20:18
int min = 0;
int max = arr.length-1;
int mid = (min+max)/2;
while(arr[mid]!=key){
if(key>arr[mid]){
min = mid+1;
}else if(key<arr[mid]){
max = mid-1;
}
if(min>max){
return -1;
}
mid = (max+min)/2;
}
return mid;
复制代码
作者:
小爷邱烙
时间:
2014-11-27 20:19
//另一种形式
int min = 0;
int max = arr.length-1;
int mid;
while(min<=max){
mid = (min+max)>>1;
if(key>arr[mid]){
min = mid+1;
}else if(key<arr[mid]){
max = mid-1;
}else{
return mid;
}
}
return -1;
复制代码
作者:
小爷邱烙
时间:
2014-11-27 20:21
for(int i=0;i<8;i++){//一个整数是4个字节,32位,四位一移,移动八次
int temp = num & 15;
if(temp>9)
System.out.println((char)(temp-10+'A'));
else
System.out.println(temp);
num = num >>>4;
}
复制代码
作者:
小爷邱烙
时间:
2014-11-27 20:22
char[] chs = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
char[] arr = new char[8];//字符数组的默认值为'\u0000',即Unicode的0000,为空格
int pos = arr.length;//定义指针,用于循环
while(num!=0){
int temp = num & 15;
arr[--pos] = chs[temp];//倒序,方便输出
num = num >>>4;
}
//此时,正负的问题也解决了
复制代码
作者:
小爷邱烙
时间:
2014-11-27 20:23
public static void trans(int num,int base,int offset){
if(num==0){
System.out.println(0);
return ;
}
char[] chs = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
char[] arr = new char[32];
int pos = arr.length;
while(num!=0){
int temp = num & base;
arr[--pos] = chs[temp];
num = num >>> offset;
}
for(int i=pos;i<arr.length;i++){
System.out.print(arr[i]);
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-7 19:50
class Person{
private int age;
Person(int age){
this.age = age;
}
public boolean compare(Person p){
return this.age == p.age;//描述功能时,还没有对象。此时需要用到调用该函数的对象,用this
}
}
class PersonDemo{
public static void main(String[] args){
Person p1 = new Person(20);
boolean b = p1.compare(new Person(20));
System.out.println(b);
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-7 20:00
//构造函数之间的调用,使用this
class Person{
private String name;
private int age;
Person(String name){
this.name = name;
}
Person(String name,int age){
this(name);//本类构造函数间调用,必须这么写
this.age = age;
}
}
//Person p = new Person("lisi",30);
//执行过程:this("lisi");p("lisi");new Person("lisi");
/*
注意:this();只能定义在构造函数的第一行,由于构造函数是初始化动作,相对于外层构造函数的一般操作动作,
初始化必须先执行。
构造函数间不允许循环调用(A调用B,B调用A)
一般函数不能调用构造函数
*/
复制代码
作者:
小爷邱烙
时间:
2014-12-7 20:25
类上注释
/**
*类的介绍
*@author 作者
*@version 版本
*/
方法上注释(public protected)其他权限不会被制作帮助文档
/**
* 功能简介
* @param 参数 参数介绍 可以写多个,一行一个
* @return 返回值介绍
*/
复制代码
作者:
禾青青
时间:
2014-12-7 23:13
学习了 谢谢
作者:
小爷邱烙
时间:
2014-12-8 16:46
//饿汉式
class Single{
private static Single s = new Single();
private Single(){}
public static Single getInstance(){
return s;
}
}
复制代码
//懒汉式
class Single{
private static Single s = null;
private Single(){}
public static Single getInstance(){
if(s==null){
synchronized (Single.class){
if(s==null){
s = new Single();
}
}
}
return s;
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-8 17:49
//获取当前时间:System.currentTimeMillis();返回long 时间毫秒与1970年1月1日午夜的时间差
abstract class GetTime{
public abstract void run();
public final void getTime(){
long start = System.currentTimeMillis();
run();
long end = System.currentTimeMillis();
System.out.println("毫秒:"+(end-start));
}
}
//模版方法模式:定义功能时,一部分是确定的,另一部分是不确定的,并且确定
//的部分在使用不确定的部分,把不确定的部分暴露出去,让子类去实现
复制代码
作者:
小爷邱烙
时间:
2014-12-8 19:11
//接口:降低耦合,提高扩展(子类实现方法),定义规则
//多态:提高扩展(符合规则的类都可以纳入体系)
//多态实例:主体调用接口
interface PCI{
public void open();
public void close();
}
class MainBoard{
public void run(){
System.out.println("mainboard run");
}
public void usePCI(PCI p){
//if(p!=null)
p.open();
p.close();
}
}
class NetCard implements PCI{
public void open() {
System.out.println("netcard open");
}
public void close() {
System.out.println("netcard close");
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-8 19:41
abstract class AbsDemo{
abstract void show();
}
class Outer{
int x = 3;
public void function(){
new AbsDemo(){
void show(){
System.out.println(x);
}
}.show();
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-8 21:03
class Demo{
int div(int a,int b){
return a/b;//2、出现异常并被JVM识别,封装为AritchmeticException 3、抛给main函数
}
}
class ExceptionDemo{
public static void main(String[] args){
Demo d = new Demo();
try{//4、被try检测到(没有try时,main函数直接将问题交给JVM,调用异常处理机制)
int x = d.div(4, 0);//1、参数传给形参进行运算
System.out.println(x);//不执行
}catch(Exception e){//5、将异常交给catch捕获,被catch形参接收
System.out.println(".....");//6、执行处理代码,try...catch代码块到此结束
}
System.out.println("over");//7、继续向下执行
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-8 21:50
private String msg;//Throwable中已经有一个private String message;并提供了getter以及构造函数赋值方式
xxxException(String msg){//xxxException(String msg){
this.msg = msg; // super(msg);
} //}即可,除此之外,自定义异常类中可以定义自己的方法,特有数据
public String getMessage(){
return msg;
}
//toString 内部调用getMessage
复制代码
作者:
小爷邱烙
时间:
2014-12-27 09:20
/*
*售票:多窗口同时售票
*/
class Ticket extends Thread{
private static int t = 100;
public void run(){
while(true){
if(t>0){
System.out.println(Thread.currentThread().getName()+"...sale:"+t--);
}
}
}
}
class TicketDemo{
public static void main(String[] args) {
Ticket t1 = new Ticket();
Ticket t2 = new Ticket();
t1.start();
t2.start();
}
}
/*
*问题:
* 1、线程间数据共享,使用静态解决,不推荐静态,静态的生命周期太长
* 2、 票不按数序出售:单核不会出现,多核时,会出现1号票出售,但未打印前,2号票同时完成出售+打印,之后1号票才打印的情况
* 3、当同一个线程被多次启动时,会抛出IllegalThreadStateException:无效的线程状态异常。stat只针对线程创建状态
*/
复制代码
作者:
小爷邱烙
时间:
2014-12-27 09:38
//模拟线程安全问题
class Ticket implements Runnable{
private int t = 100;
public void run() {
while(true){
if(t>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t--);
}
}
}
}
/*
*注意:run方法不能抛出异常,因为run方法是继承来的,其父类/接口中的run方法未抛出任何异常,所以必须try
* 多线程必须要十分小心安全问题,因为测试时可能测不出来
*问题:多条语句操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完,
* 另一个线程参与进来执行,导致共享数据的错误
*解决办法:对多条操作共享数据的语句,只能让一个线程都执行完,在执行过程中,其他线程不可以参与执行
*/
复制代码
作者:
小爷邱烙
时间:
2014-12-27 09:52
class Bank{
private int sum;
public synchronized void add(int n){
sum = sum + n;
System.out.println(sum);
}
}
class Cus implements Runnable{
private Bank b = new Bank();
public void run(){
for(int x=0;x<3;x++){
b.add(100);
}
}
}
/*
* 判断是否需要同步:1、哪些是多线程 2、是否共享数据 3、多线程哪些语句在操作共享数据
* 本例子中,run方法中的语句有操作共享数据,调用add方法,所以add方法需要同步。
* 此时不要在run中同步,run中同步,相当于单线程,要在add中同步。
*/
复制代码
作者:
小爷邱烙
时间:
2014-12-27 10:06
//验证:两个线程,一个同步代码块(锁为其他则二线程不同步,锁为this则同步),一个同步函数。
//实现:两个线程执行不同代码,定义一个flag,true执行一部分run,false执行另一部分run
class Ticket implements Runnable{
private int tick = 100;
Object obj = new Object();
boolean flag = true;
public void run(){
if(flag){
while(true){
synchronized (obj) {//当锁为this时,同步
if(tick>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"..code:"+tick--);
}
}
}
}else{
while(true){
show();
}
}
}
public synchronized void show(){
if(tick>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"..show:"+tick--);
}
}
}
class ThisLockDemo{
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try {
Thread.sleep(100);//防止t1启动后不执行,直接改变flag,造成混乱
} catch (InterruptedException e) {
e.printStackTrace();
}
t.flag = false;
t2.start();
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-27 10:11
class Single{
private static Single s = null;
private Single(){}
public static Single getInstance(){//使用同步函数低效
if(s==null){
synchronized (Single.class) {//静态锁
if(s==null){
s = new Single();
}
}
}
return s;
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-27 10:21
class SynAddRunnable implements Runnable{
int a,b;
public SynAddRunnable(int a,int b){
this.a = a;
this.b = b;
}
public void run(){
synchronized (Integer.valueOf(a)) {
synchronized (Integer.valueOf(b)) {//Integer.valueOf为了节省资源,同一个数字只创建一个对象
System.out.println(a+b);
}
}
}
public static void main(String[] args) {
for(int x=0;x<100;x++){
new Thread(new SynAddRunnable(1, 2)).start();
new Thread(new SynAddRunnable(2, 1)).start();
}
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-27 10:41
class Ticket implements Runnable{
private int tick = 100;
Object obj = new Object();
boolean flag = true;
public void run(){
if(flag){
while(true){
synchronized (obj) {//代码块中有函数中有代码块
show();
}
}
}else{
while(true){
show();
}
}
}
public synchronized void show(){
synchronized (obj) {
if(tick>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"...code:"+tick--);
}
}
}
}
class DeadLockDemo{
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.flag = false;
t2.start();
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-27 10:57
class Testa implements Runnable{
private boolean flag;
Testa(boolean flag){
this.flag = flag;
}
public void run(){
if(flag){
while(true){
synchronized (MyLock.locka) {
System.out.println("if locka");
synchronized (MyLock.lockb) {
System.out.println("if lockb");
}
}
}
}else{
while(true){
synchronized (MyLock.lockb) {
System.out.println("else lockb");
synchronized (MyLock.locka) {
System.out.println("else locka");
}
}
}
}
}
}
class MyLock{
static Object locka = new Object();
static Object lockb = new Object();
}
class DeadLockTest{
public static void main(String[] args) {
new Thread(new Testa(true)).start();
new Thread(new Testa(false)).start();
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-27 19:35
class Res{
String name;
String sex;
}
class Input implements Runnable{
private Res r;
Input(Res r){
this.r = r;
}
public void run(){
int x = 0;
while(true){
synchronized (r) {//r对象唯一,也可以用class对象
if(x==0){
r.name = "mike";
r.sex = "man";
}else{
r.name = "丽丽";
r.sex = "女";
}
x = (x+1)%2;
}
}
}
}
class Output implements Runnable{
private Res r;
Output(Res r){
this.r = r;
}
public void run(){
while(true){
synchronized (r) {
System.out.println(r.name+"..."+r.sex);
}
}
}
}
class InputOutputDemo{
public static void main(String[] args) {
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-27 20:08
class Resource{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name){//生产和消费线程有相同的锁,生产时不能消费,消费时不能生产
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
flag = true;
this.notify();
}
public synchronized void get(){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
flag = false;
this.notify();
}
}
class Producer implements Runnable{//生产者
private Resource res;
Producer(Resource res){
this.res = res;
}
public void run(){
while(true){
res.set("商品");
}
}
}
class Consumer implements Runnable{
private Resource res;
Consumer(Resource res){
this.res = res;
}
public void run(){
while(true){
res.get();
}
}
}
class ProducerConsumerDemo{
public static void main(String[] args) {
Resource res = new Resource();
new Thread(new Producer(res)).start();
new Thread(new Consumer(res)).start();
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-27 21:18
import java.util.concurrent.locks.*;
class ProducerConsumerDemo2{
public static void main(String[] args) {
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource{
private String name;
private int count = 1;
private boolean flag = false;
private Lock lock = new ReentrantLock();
private Condition condition_pro = lock.newCondition();
private Condition condition_con = lock.newCondition();
public void set(String name)throws InterruptedException{
lock.lock();
try{
while(flag)
condition_pro.await();
this.name = name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
flag = true;
condition_con.signal();
}finally{
lock.unlock();
}
}
public void get()throws InterruptedException{
lock.lock();
try{
while(!flag)
condition_con.await();
System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
flag = false;
condition_pro.signal();
}finally{
lock.unlock();
}
}
}
class Producer implements Runnable{
private Resource res;
Producer(Resource res){
this.res = res;
}
public void run(){
while(true){
try{
res.set("商品");
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
private Resource res;
Consumer(Resource res){
this.res = res;
}
public void run(){
while(true){
try{
res.get();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-27 21:31
class StopThread implements Runnable{
private boolean flag = true;
public synchronized void run(){
while(flag){
try{
wait();
}catch(InterruptedException e){
System.out.println(Thread.currentThread().getName()+"...Exception");
changeFlag();
}
System.out.println(Thread.currentThread().getName()+"...run");
}
}
public void changeFlag(){
flag = false;
}
}
class StopThreadDemo{
public static void main(String[] args) {
StopThread st = new StopThread();
Thread t1 = new Thread(st);
Thread t2 = new Thread(st);
t1.start();
t2.start();
int num = 0;
while(true){
if(num++==60){
t1.interrupt();
t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName()+"..."+num);
}
System.out.println("over");
}
}
复制代码
作者:
小爷邱烙
时间:
2014-12-27 21:47
new Thread(){
public void run(){
for(int x=0;x<100;x++){
System.out.println(Thread.currentThread().getName()+"..."+x);
}
}
}.start();
复制代码
作者:
小爷邱烙
时间:
2014-12-28 10:12
/*
*练习一:模拟一个trim方法,去除字符串两端的空格
*思路:1、判断第一个位置是否是空格,依次直到不是空格为止。判断最后一个是否空格,依次直到不是空格为止
* 2、开头和结尾都不是空格时,根据角标获取子串
*/
public static String myTrim(String str){
int start = 0,end = str.length()-1;
while(start<=end && str.charAt(start)==' '){
start++;
}
while(start<=end && str.charAt(end)==' '){
end--;
}
return str.substring(start, end+1);
}
复制代码
作者:
小爷邱烙
时间:
2014-12-28 10:22
/*
*练习二:将字符串指定的部分反转
*思路:将字符串变成数组,将数组反转,将数组变成字符串
*/
public static String reverseString(String s,int start,int end){
char[] chs = s.toCharArray();
reverse(chs,start,end);
return new String(chs);
}
private static void reverse(char[] arr,int x,int y){
for(int start=x,end=y-1;start<end;start++,end--){//y-1,包含头不包含尾,约定俗成
swap(arr,start,end); //java定义成这样方便传length得到length-1
}
}
private static void swap(char[] arr,int x,int y){
char temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
public static String reverseString(String s){
return reverseString(s,0,s.length());
}
复制代码
作者:
小爷邱烙
时间:
2014-12-28 10:28
/*
*练习三:获取一个字符串中另一个字符串出现的次数
*思路:定义一个计数器,获取子串第一次出现的位置,从第一次出现位置后剩余的字符串中继续获取子串出现的位置,每获取一次,
* 就计数一次,当获取不到时,计数完成
*/
public static int getSubCount(String str,String key){
int count = 0;
int index = 0;
while((index=str.indexOf(key))!=-1){
str = str.substring(index+key.length());
count++;
}
return count;
}
复制代码
作者:
小爷邱烙
时间:
2014-12-28 10:48
/*
*方式二:方式一在内存中产生太多字符串
*/
public static int getSubCount(String str,String key){
int count = 0;
int index = 0;
while((index=str.indexOf(key, index))!=-1){
index = index + key.length();
count++;
}
return count;
}
复制代码
作者:
小爷邱烙
时间:
2014-12-28 10:56
/*
*练习四:取两个字符串中最大相同子串
*思路:获取两个字符串中较短的那个,获取一个字符串从长到短的子串,判断子串是否在长串中
*/
public static String getMaxSubString(String s1,String s2){
String max = (s1.length()>s2.length())?s1:s2;
String min = (max==s1)?s2:s1;
for(int x=0;x<min.length();x++){
for(int y=0,z=min.length()-x;z!=min.length()+1;y++,z++){
String temp = s2.substring(y,z);
if(max.contains(temp)){
return temp;
}
}
}
return "";
}
复制代码
作者:
小爷邱烙
时间:
2015-1-8 15:29
Collection 接口 java.util包 JDK1.2出现
|——List 接口
|——ArrayList
|——LinkedList
|——Vector
|——Set 接口
|——HashSet
|——TreeSet
每一个容器对数据的存储方式都不同,存储方式称为数据结构
复制代码
作者:
小爷邱烙
时间:
2015-1-8 15:53
boolean add(E e)//集合对象在堆内存中,和数组一样,存储的是元素在堆内存中的地址
boolean addAll(Collection c)//把指定集合中的元素添加到此集合中
void clear()//清空集合
boolean remove(Object o)//移除指定元素,只移除第一次出现的
boolean removeAll(Collection c)//移除交集
boolean contains(Object o)//判断是否包含该元素
boolean containsAll(Collection c)//必须包含所有元素才返回true
boolean equals(Object o)//集合与对象是否相同
boolean isEmpty()//集合是否为空
int size()//集合中元素数
boolean retainAll(Collection c)//取交集,仅保留两个集合中都有的元素,属于改
Object[] toArray()//返回所有元素的数组
<T> T[] toArray(T[] a)//按泛型返回数组,必须所有元素都是泛型指定类型
String toString()//Collection的toString方法重写了Object的toString方法,
//不再打印哈希值,而以一对[]中括号为边界,打印集合中元素
Collection的操作没有取出,需要一个方法
Iterator<T> iterator()//返回集合的迭代器,由迭代器做取出
复制代码
作者:
小爷邱烙
时间:
2015-1-8 16:14
Iterator<E> it = al.iterator();//返回一个Iterator的子类对象,至于是什么对象,已经被封装了,这里是多态
while(it.hasNext()){
System.out.println(it.next());
}
复制代码
作者:
小爷邱烙
时间:
2015-1-8 16:24
for(Iterator it=al.iterator();it.hasNext();){
System.out.println(it.next());
}
复制代码
作者:
小爷邱烙
时间:
2015-1-8 16:35
void add(int index,E e)
boolean addAll(int index,Collection c)//在指定位置添加
E get(int index)//获取
int indexOf(Object o)
int lastIndexOf(Object o)//判断位置
ListIterator listIterator()//List特有迭代器
ListIterator listIterator(int index)//从指定位置开始
E remove(int index)
E set(int index,E e)//替换
List subList(int fromIndex,int toIndex)//包含头,不包含尾
复制代码
作者:
小爷邱烙
时间:
2015-1-8 16:38
for(int x=0;x<al.size();x++){
System.out.println(al.get(x));
}
复制代码
作者:
小爷邱烙
时间:
2015-1-8 16:47
void add(E e)//在被迭代的最后一个元素后添加
int nextIndex()//获取下一个元素的角标
void set(E e)//修改被迭代的最后一个元素
boolean hasPrevious()//逆向迭代,同next
E previous()
int previousIndex()
这些都是ListIterator特有方法,因为只有List有角标
复制代码
作者:
小爷邱烙
时间:
2015-1-8 17:53
void addFirst(E e)
void addLast(E e)
E getFirst()
E getLast()
E removeFirst()
E removeLast()
get系列方法:获取元素
remove系列方法:获取元素,并且删除元素
一种由remove方法实现的获取,LinkedList特有方法
while(!link.isEmpty()){
System.out.println(list.removeFirst())
}
当LinkedList中为空时,remove,get抛出NoSuchElementException
复制代码
作者:
小爷邱烙
时间:
2015-1-8 17:57
E pollFirst()//相当于remove
E pollLast()
E peekFirst()//相当于get
E peekLast()
boolean offerFirst(E e)//相当于add
boolean offerLast(E e)
这一系列方法当List为空时,返回null,不抛出异常
复制代码
作者:
小爷邱烙
时间:
2015-1-8 18:03
import java.util.LinkedList;
/*练习:使用LinkedList模拟一个堆栈,队列数据结构
*堆栈:先进后出
*队列:先进先出
*/
class DuiLie{
private LinkedList link;
DuiLie(){
link = new LinkedList();
}
public void myAdd(Object obj){
link.addFirst(obj);
}
public Object myGet(){
return link.getLast();
}
public boolean isNull(){
return link.isEmpty();
}
}
//javaweb中的session appication域都是这种封装方式
复制代码
作者:
小爷邱烙
时间:
2015-1-8 18:07
import java.util.ArrayList;
import java.util.Iterator;
//练习:除去ArrayList中的重复元素
class Test{
public static ArrayList singleElement(ArrayList<E> al){
ArrayList newAl = new ArrayList();
Iterator it = al.iterator();
while(it.hasNext()){
Object obj = it.next();
if(!newAl.contains(obj))
newAl.add(obj);
}
return newAl;
}
}
复制代码
作者:
小爷邱烙
时间:
2015-1-8 18:16
/*
* 练习:将自定义对象作为元素存储到ArrayList中,并去除重复元素
* Person同名同年龄视为同一个人,为重复元素
* List集合的contains方法判断元素是否相同,用的是元素的equals方法
* 由此,remove方法的寻找也用equals
*/
class Person{
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
Person p = (Person) obj;
return this.name.equals(p.name) && this.age==p.age;
}
}
//注意,在没有泛型的情况下,迭代器获取的是Object,需要做强转
复制代码
作者:
小爷邱烙
时间:
2015-1-8 18:36
public int hashCode(){
return name.hashCode()+age*39;//防止出现40+20=20+40的情况,乘以一个任意数,尽量保证哈希值唯一。
}
复制代码
作者:
小爷邱烙
时间:
2015-1-8 18:55
public int compareTo(Object o){
return 1;
}
复制代码
作者:
小爷邱烙
时间:
2015-1-8 19:03
//使用构造函数 TreeSet(Comparator comparator)
class Mycompare implements Comparator{
public int compare(Object o1,Object o2){}
}
复制代码
作者:
小爷邱烙
时间:
2015-1-8 19:22
/*
* 练习:向TreeSet中存入字符串,按字符串长度排序
* String本身具备比较性,但不符合要求,要使用比较器
*/
class StringLengthComparator implements Comparator{
public int compare(Object o1,Object o2){
String s1 = (String)o1;
String s2 = (String)o2;
if(s1.length()>s2.length())
return 1;
if(s1.length()==s2.length())
return s1.compareTo(s2);
return -1;
}
}
/*
* 可改为
* int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
* if(num==0)
* return s1.compareTo(s2);
* return num;
*/
/*
* 可以使用匿名内部类
* TreeSet ts = new TreeSet(new Comparator{
* public int compare(Object o1,Object o2){}
* })
*/
复制代码
作者:
小爷邱烙
时间:
2015-1-8 19:42
class Utils<T>{
private T t;
public void setObject(T t){
this.t = t;
}
public T getObject(){
return t;
}
}
复制代码
作者:
小爷邱烙
时间:
2015-1-8 20:32
class InterImpl implements Inter<String>{
public void show(String str){
System.out.println("show"+s);
}
}
复制代码
作者:
小爷邱烙
时间:
2015-1-8 20:34
//继承泛型:此时创建对象时明确泛型
class InterImpl<T> implements Inter<T>{
public void show(T t){
System.out.println("show"+t);
}
}
复制代码
作者:
小爷邱烙
时间:
2015-1-9 11:08
void chear()
boolean containsKey(Object key)
boolean containsValue(Object value)
V get(Object key)//获取返回null可用于判断键是否存在
boolean isEmpty()
V put(K key,V value)//当存相同键时,新值替换老值,返回老值,首次存入键返回null
void putAll(Map m)
V remove(Object key)
int size()
Collection values()
Set entrySet()
Set keySet()
String toString()//返回的是{key=value,key=value}
复制代码
作者:
小爷邱烙
时间:
2015-1-9 11:17
Set<String> keySet = map.keySet();
Iterator<String> it = keySet.iterator();
while(it.hasNext()){
String key = it.next();
String value = map.get(key);
System.out.println(key+"..."+value)
}
//keySet返回本集合所有键,存入Set中
复制代码
作者:
小爷邱烙
时间:
2015-1-9 11:20
Set<Map.Entry<String,String>> entrySet = map.entrySet();
Iterator<Map.Entry<String,String>> it = entrySet.iterator();
while(it.hasNext()){
Map.Entry<String,String> me = it.next();
String key = me.getKey();
String value = me.getValue();
}
复制代码
作者:
小爷邱烙
时间:
2015-1-9 11:40
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
//练习:获取字母出现次数
class Test{
public static String charCount(String str){
char[] chs = str.toCharArray();
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
int count = 0;
for(int x=0;x<chs.length;x++){
if(!((chs[x]>='a' && chs[x]<='z') || (chs[x]>='A' && chs[x]<='Z')))
continue;
Integer value = tm.get(chs[x]);
if(value!=null)
count = value;
count++;
tm.put(chs[x], count);
count = 0;
}
StringBuilder sb = new StringBuilder();
Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();
Iterator<Map.Entry<Character,Integer>> it = entrySet.iterator();
while(it.hasNext()){
Map.Entry<Character, Integer> me = it.next();
Character ch = me.getKey();
Integer value = me.getValue();
sb.append(ch+"("+value+")");
}
return sb.toString();
}
}
复制代码
作者:
小爷邱烙
时间:
2015-1-9 12:03
static <T extends Comparable<? super T>> void sort(List<T> list)
//当List元素具备比较性时,对List排序。也可以传比较器
static <T> void sort(List<t> list,Comparator<? super T> )
static <T extends Object&Comparable<? super T>> T max(Collection<? extends T> coll)
//根据自然排序,取集合的最大元素,也可以传比较器。min方法类似
static <T> int binarySearch(List<? extends Comparable<? super T>> list,T key)
//对集合进行二分查找。也可以使用比较器。注意使用比较器时,排序和二分查找要用同一个比较器。
//二分查找的前提是集合有序。二分查找当找不到时,返回-插入点-1
static <T> void fill(List<? super T> list,T obj)
//用指定元素obj替换集合中的所有元素
static boolean replaceAll(List<T> list,T oldVal,T newVal)
//替换指定元素
static void reverse(List<?> list)
//反转集合
static <T> comparator<T> reverseOrder()
//返回一个自然排序的逆序比较器
static <T> comparator<T> reverseOrder(Comparator<T> cmp)
//将一个比较器逆转返回
static Collection<T> synchronizedCollection(Collection<T> c)
//一系列方法将传入的集合转成线程同步的并返回,其底层实现用同锁同步代码块,Collection,Map,List,Set都有该方法
static void swap(List<?> list,int i,int j)
//交换元素位置
static void shuffle(List<?> list)
//随机重置集合中元素位置
复制代码
作者:
小爷邱烙
时间:
2015-1-9 12:22
static int binarySearch(int[] a,int key)
//一系列方法,二分查找,也可以设置起始位置,结束位置。byte[],char[],double[],float[]
//long[],Object[],short[],T[]都有该方法
static int[] copyOf(int[] arr,int newLength)
//一系列方法,数组复制。各数据类型都有。copyOfRange(int[] arr,int from,int to)复制一个范围
static boolean equals(int[] a,int[] b)
//一系列方法,比较数组。比较的是元素,要元素和顺序都一致。各类型都有。
static void fill(int[] a,nt val)
//一系列方法,替换数组值,可指定范围,各类型都有
static void sort(int[] a)
//一系列方法,排序,可指定范围,各类型都有
static String toString()
//一系列方法,返回数组内容的字符串
复制代码
作者:
李票
时间:
2015-1-9 19:55
谢谢楼主分享,有的看过了有的学习了
作者:
小爷邱烙
时间:
2015-1-11 11:04
static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
//修改dest数组,从srcPos开始截取,截取length个,从destPos开始覆盖
static long currentTimeMillis()
//返回当前时间毫秒值
static void exit(int status)
//终止JVM 等效于 Runtime.getRuntime().exit(n)
static void gc()
//执行垃圾回收器
static Properties getProperties()
//System类会描述系统环境,记录系统启动时的加载信息。该方法获取系统属性信息。
//获取的JVM,JDK以及当前操作系统的一些信息
Properties:HashTable的子类,与IO相关。其作为一个集合,可以取也可以存。
//注意该Properties取出时是<Object,Object>,存入时则是<String,String>
//java的一个命令参数java -Dkey=value能在启动JVM时动态的为系统添加一些信息。
复制代码
作者:
小爷邱烙
时间:
2015-1-11 11:42
static int abs(int a)//取绝对值,float long double都有
static double ceil(double a)//入,注意小数
static double floor(double a)//舍,注意小数
static int round(float a)//四舍五入 long-double也有
static double pow(double a,double b)//a的b次方
static double random()//返回一个0.0~1.0的随机小数,包含0不包含1
java.util包中有一个Random类,可以直接new,其全部方法就是各种next。
常用int r.nextInt(n) 0~n的随机数,不包含n
复制代码
作者:
Afridoce
时间:
2015-1-11 14:54
lz加油~~~~
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2