声明:本次本人整理,内容个人学习还涉及老师教的。主要做笔记,有什么建议一起交流!
目录:
一,集合
二,泛型
三,枚举
四,IO流
五,多线程
六,常用类
七,反射机制
八,网络编程
九,了解Java8
正文:
一,集合:
问题:为什么不使用数组而用集合?
学习内容:
- ArrayList(Collection-->List下)有序,可重复
- HashSet(Collection-->Set下)无序,不重复
- HashMap(Map下)
1.ArrayList:有序,可重复
- 更适合查找和更新(因为它是尾部插入和删除)
- 元素可以NULL
操作:ArrayList存储数据
import java.util.ArrayList;
import java.util.List;
public class ListDome {
public static void main(String[]args){
//用ArrayList存储数据
List list =new ArrayList();
//添加数据
list.add("Java");
list.add("C++");
list.add("C#");
//输出
System.out.println("列表的个数"+list.size());
System.out.println("==============");
//遍历
System.out.println("遍历:");
for (int i=0;i<list.size();i++){
System.out.println(list.get(i)+",");
}
//移除第二个(方案一)
System.out.println("==============");
list.remove(2);
//移除第二个(方案二)使用方案二时需要注销方案一
System.out.println("=======移除第二个(方案二)=======");
list.remove("C#");
System.out.println("移除第二个之后的");
for (int i=0;i < list.size();i++)
{
System.out.println(list.get(i)+",");
}
}
}
2.HashSet:无序,不重复
- 只允许一个NULL元素
- 具有良好的存取和查找功能
3.HashMap
- 以“键值对(key-value)”形式保存
- 键(key)不可以重复
- 基于哈希表的Map接口
二,泛型
泛型解决存储安全性和类型强转问题
集合中不使用泛型
//集合中不使用泛型
public void Genericity(){
List list = new ArrayList();
list.add(23);
list.add(12);
list.add(34);
//1.没有使用泛型,任何Object及其子类的对象都可以添加进来
list.add(new String("AA"));
for(int i = 0;i < list.size();i++){
//2.强转为int型时,可能报ClassCastException的异常
int score = (Integer)list.get(i);
System.out.println(score);
}
}
集合中使用泛型
//集合中使用泛型
public void Genericity02(){
List list = new ArrayList();
list.add(12);
list.add(21);
list.add(23);
//1.没有使用泛型,任何Object及其子类的对象都可以添加进来
list.add(new String("AA"));
//for(int i = 0;i < list.size();i++){
//2.强转为int型时,可能报ClassCastException的异常
// int score = (Integer)list.get(i);
// System.out.println(score);
Iterator<Integer> it = list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
public void Genericity03(){
Map<String,Integer> map = new HashMap<>();
map.put("AA", 34);
map.put("BB", 45);
map.put("DD", 23);
Set<Map.Entry<String,Integer>> set = map.entrySet();
for(Map.Entry<String,Integer> o : set){
System.out.println(o.getKey() + "--->" + o.getValue());
}
}
泛型和继承的关系:
A类是B类的子类,G类带泛型的类或者接口。是G<A>而不是G<B>
泛型的应用:
public class DAO<T> {
public void add(T t){
//....
}
public T get(int index){
return null;
}
public List<T> getForList(int index){
return null;
}
public void delete(int index){
}
}
public class CustomerDAO extends DAO<Customer>{
}
public class TestCustomerDAO {
public static void main(String[] args) {
CustomerDAO c = new CustomerDAO();
c.add(new Customer());
c.get(0);
}
}
三,枚举
使用enum关键字声明
四,IO流
设备数据传输
分类:
- 数据流向不同:输入流,输出流
- 处理数据单位:字节流(8bit),字符流(16bit)
- 处理角色不同:节点流,处理流
IO体系:
- 抽象基类:
- InputStream
- OutputStream
- Reader
- Writer
- 字节流
- FileInputStream (int read(byte[] b))
- FileOutputStream (void write(b,0,len))
- FileReader (int read(char[] c))
- FileWriter (void write(c,0,len))
- 处理流
- BufferedInputStream (int read(byte[] b))
- BufferedOutputStream (flush()) (void write(b,0,len))
- BufferedReader (readLine()) (int read(char[] c))或String readLine() BufferedReader (readLine()) (int read(char[] c))或String readLine()
五,多线程
创建(使用继承(extends)即可)
- Thread
- Runnable
线程生命周期:
线程同步机制:
多个线程数据容易问题
- 同步代码块
synchronized(同步监视器){
//操作共享数据的代码
}
-
同步监视器:俗称锁,任何一个类的对象都可以才充当锁。要想保证线程的安全,必须要求所有的线程共用同一把锁
-
使用实现 Runnable 接口的方式创建多线程的话,同步代码块中的锁,可以考虑是this。如果使用继承 Thread 类的方式,慎用 this
-
共享数据:多个线程需要共同操作的变量。 明确哪部分是操作共享数据的代码。
- 同步方法——将操作共享数据的方法声明为synchronized
public synchronized void show(){ //操作共享数据的代码}
- 对于非静态的方法而言,使用同步的话,默认锁为:this。如果使用在继承的方式实现多线程的话,慎用
- 对于静态的方法,如果使用同步,默认的锁为:当前类本身。以单例的懒汉式为例。 Class clazz = Singleton.class释放锁:wait();
- 不释放锁: sleep() yield() suspend() (过时,可能导致死锁)
六,常用类
- String类
- 添加:append(...)
- 删除 delete(int startIndex, int endIndex)
- 修改:setCharAt(int n ,char ch)
- 查询:charAt(int index)
- 插入:insert(int index, String str)
- 反转reverse()
- 长度:length()
- System类:
- currentTimeMillis()从1970年1月1日0点0分00秒开始到当前的毫秒数。此方法常用来计算时间差。
- Date 类:java.util.Date
- Calendar类
- Math类
- BigInteger BigDecimal类
七,反射机制
动态语言的关键
- Java 反射机制提供的功能:
- 在运行时判断任意一个对象所属的类
- 在运行时构造任意一个类的对象
- 在运行时判断任意一个类所具有的成员变量和方法
- 在运行时调用任意一个对象的成员变量和方法
- 生成动态代理
Class的应用:
- 可以创建对应的运行时类的对象(重点)
//获取运行时类的对象:方法一
@Test
public void test1() throws Exception{
Class clazz = Class.forName("com.atguigu.review.Animal");
Object obj = clazz.newInstance();
Animal a = (Animal)obj;
System.out.println(a);
}
//调用指定的构造器创建运行时类的对象
@Test
public void test2() throws Exception{
Class clazz = Animal.class;
Constructor cons = clazz.getDeclaredConstructor(String.class,int.class);
cons.setAccessible(true);
Animal a = (Animal)cons.newInstance("Tom",10);
System.out.println(a);
}
- 调用对应的运行时类中指定的结构(某个指定的属性、方法、构造器)(重点)
//调用指定属性
@Test
public void test3() throws Exception{
Class clazz = Class.forName("com.atguigu.review.Animal");
Object obj = clazz.newInstance();
Animal a = (Animal)obj;
//调用非public的属性
Field f1 = clazz.getDeclaredField("name");
f1.setAccessible(true);
f1.set(a, "Jerry");
//调用public的属性
Field f2 = clazz.getField("age");
f2.set(a, 9);
System.out.println(f2.get(a));
System.out.println(a);
//调用static的属性
Field f3 = clazz.getDeclaredField("desc");
System.out.println(f3.get(null));
}
//调用指定的方法
@Test
public void test4() throws Exception{
Class clazz = Class.forName("com.atguigu.review.Animal");
Object obj = clazz.newInstance();
Animal a = (Animal)obj;
//调用非public的方法
Method m1 = clazz.getDeclaredMethod("getAge");
m1.setAccessible(true);
int age = (Integer)m1.invoke(a);
System.out.println(age);
//调用public的方法
Method m2 = clazz.getMethod("show", String.class);
Object returnVal = m2.invoke(a,"金毛");
System.out.println(returnVal);
//调用static的方法
Method m3 = clazz.getDeclaredMethod("info");
m3.setAccessible(true);
// m3.invoke(Animal.class);
m3.invoke(null);
}
八,网络编程
- TCP编程(Socket ServerSocket)
- 客户端给服务端发送信息,同时服务端发送“已收到信息”给客户端
//TCP编程例:客户端给服务端发送信息,服务端将信息打印到控制台上,同时发送“已收到信息”给客户端
public class TestTCP2 {
//客户端
@Test
public void client(){
Socket socket = null;
OutputStream os = null;
InputStream is = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"),8989);
os = socket.getOutputStream();
os.write("我是客户端".getBytes());
//shutdownOutput():执行此方法,显式的告诉服务端发送完毕!
socket.shutdownOutput();
is = socket.getInputStream();
byte[] b = new byte[20];
int len;
while((len = is.read(b)) != -1){
String str = new String(b,0,len);
System.out.print(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(os != null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//服务端
@Test
public void server(){
ServerSocket ss = null;
Socket s = null;
InputStream is = null;
OutputStream os = null;
try {
ss = new ServerSocket(8989);
s = ss.accept();
is = s.getInputStream();
byte[] b = new byte[20];
int len;
while((len = is.read(b)) != -1){
String str = new String(b,0,len);
System.out.print(str);
}
os = s.getOutputStream();
os.write("我已收到你的情意".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(os != null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(is != null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(s != null){
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ss != null){
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
- UDP编程(DatagramSocket DatagramPacket)
//UDP编程的实现
public class TestUDP {
// 发送端
@Test
public void send() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
byte[] b = "你好,我是要发送的数据".getBytes();
//创建一个数据报:每一个数据报不能大于64k,都记录着数据信息,发送端的IP、端口号,以及要发送到
//的接收端的IP、端口号。
DatagramPacket pack = new DatagramPacket(b, 0, b.length,
InetAddress.getByName("127.0.0.1"), 9090);
ds.send(pack);
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(ds != null){
ds.close();
}
}
}
// 接收端
@Test
public void rceive() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket(9090);
byte[] b = new byte[1024];
DatagramPacket pack = new DatagramPacket(b, 0, b.length);
ds.receive(pack);
String str = new String(pack.getData(), 0, pack.getLength());
System.out.println(str);
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(ds != null){
ds.close();
}
}
}
}