java基础(面试)

来源:互联网 发布:c语言编写 玫瑰花 编辑:程序博客网 时间:2024/05/20 18:49

InputStream转byte[] :

public static byte[] InputStreamTobytearray(InputStream in){      ByteArrayOutputStream out=new ByteArrayOutputStream();     byte[] buff=new buff[1024];  //缓存区     int length=0;     while((length=in.read(buff))!=-1){         out.write(buff,0,length);     }     out.close;     in.close;     byte[] bytes=out.toByteArray();     return bytes; }

ArrayList与LinkedList区别

  1. ArrayList是基于索引的数组类型集合,而LinkedList是基于指针的链表类型集合
  2. ArrayList的查找和读取数据是很快的,插入和删除则是很慢的(除尾插入和尾删除),因为改变数组中数据,其他数据位置索引也要发生改变。
  3. LinkedList的查找和读取数据是很慢的,因为需要指针从头开始一个一个往下查找,但是插入和删除则很快,因为只需要将插入或删除位置的前后指针指向,不需要改变其他数据
  4. LinkedList需要更多内存,因为每个节点中存储的是实际数据和前后节点的位置

总结:若经常查找与读取数据,可以用ArrayList;若经常插入和删除数据,可以用LinkedList;平时使用的比较多的是ArrayList


HashMap与HashTable区别

  • HashMap是非synchronized的,同时可以接收为null的键值对,但是Hashtable不行,它是线程安全的

二分查找法

public static int query(int[] a,int b){         int low=0,high=a.length-1;         int mid=0;         //这里注意是小于等于,low和high有重合的时候         while(low<=high){             mid=(low+high)/2;             System.out.println("mid:"+mid);             if(b<a[mid])                 high=mid-1;             else if(b>a[mid])                 low=mid+1;             else if(b==a[mid])                 return mid;         }         return -1;    }
原创粉丝点击