首页 > 代码库 > java学习笔记(一)

java学习笔记(一)

List使用

List lst = new ArrayList();//List是接口,ArrayList是实现类

list.add("hello");//添加

list.removeAt(0);//删除

list.get(0);//获得

Int32[] vals = (Int32[])list.toArray(typeof(Int32));//转换成数组

String[] attr = (String[])list.toArray(new String[list.size()]);//

//遍历foreach

List<String> lst = new ArrayList<String>();//泛型

lst.add("aaa");//.......

for (String str: lst) {....}

list1.addAll(list2);//连接list2到list1

//数组转成list

List lst = Arrays.asList("a","b","c");

String[] arr = new String[]{"hell","worl","hah"};

List lst = Arrays.asList(arr);

常用集合类的继承关系

Collection<--List<--Vector 

Collection<--List<--ArrayList 

Collection<--List<--LinkedList 

Collection<--Set<--HashSet 

Collection<--Set<--HashSet<--LinkedHashSet 

Collection<--Set<--SortedSet<--TreeSet 

Map<--SortedMap<--TreeMap 

Map<--HashMap 

Queue使用

Queue<String> que = new LinkedList<String>();

que.offer("hello");//入队列

while (que.poll() != null);//出队列

que.size();//队列大小

线程安全队列实现:http://blog.csdn.net/madun/article/details/20313269

socket udp实例

import java.net.*;
public class UdpSend {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
byte[] buf = "UDP Demo".getBytes();
DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 10000);
ds.send(dp);
ds.close();
System.out.println("data send ok!");
}
}

import java.net.*;
public class UdpReceive {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(10000);
byte[] buf = new byte[1024];
DatagramPacket dp =new DatagramPacket(buf, buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = http://www.mamicode.com/new String(dp.getData(), 0, dp.getLength());
int port = dp.getPort();
System.out.println(data + ":" + port + "@" + ip);
ds.close();
}
}

java学习笔记(一)