目录
1.基本类型
1.1储存空间
字节型 |
| ||||||
整型 |
| ||||||
浮点型 |
| ||||||
字符型 |
| ||||||
布尔型 |
|
1.2char
1.2.1 char a ='\ u0041'可表示一个汉字,基于原始的Unicode规范
1.2.2 char a = 99
一个可以直接比较:
-
char a = 99;
-
if (a < 'z' && a > 'a') {
-
System.out.println(a);
-
}
2.运算符
2.1三目运算符
布尔表达式表达式1:表达式2
练习:
当x> 0:sgn(x)= 1;
当x = 0:sgn(x)= 0;
当x <0:sgn(x)= - 1;
输入x,输出sgn(x)的值。
-
public static void function04(){
-
System.out.println("请输入x的值:");
-
Scanner scan = new Scanner(System.in);
-
int x = scan.nextInt();
-
System.out.println("sgn(x)=" + (0==x?0:(x>0?1:-1)));
-
}
2.2运算符优先级
' {} '>' ++ '>'(强制类型转换)'>' / '>' + '>' << '>' > = '>' == '>' & '>' ^ '>' | '>' && '>' || '>' ?:'>' = '
2.3“equals()方法”与“==”
equals()
注意:等于方法不能作用于基本数据类型的变量。
如果没有对等于方法进行重写,则比较的是引用类型的变量所指向的对象的地址;
诸如字符串,日期等类对等于方法进行了重写的话,比较的是所指向的对象的内容。
==
如果作用于基本数据类型的变量,则直接比较其存储的“值”是否相等;
如果作用于引用类型的变量,则比较的是所指向的对象的地址。
3.数组
3.1创建写法
int [] arr = new int [10]; //初始化
int [] arr = {1,2,3,4,5}; //初始化并赋值
int [] arr1 = new int [] {1,2,3,4,5};
3.2数组操作代码
-
//复制数组
-
int[] aa=new int[3];
-
for(int i=0;i<3;i++){
-
aa[i]=1;
-
}
-
int[] bb=Arrays.copyOf(aa, 4);
-
//1 1 1 0
-
bb=Arrays.copyOf(aa, 4);
-
//数组升序快排
-
int[] a={1,4,-1,5,0};
-
Arrays.sort(a);
-
//二分查找
-
String str[] = new String[]{"ab", "cd", "ef", "yz"};//定义String型数组str
-
Arrays.sort(str);//对数组进行排序
-
int index = Arrays.binarySearch(str, 0, 2, "cd");//在制定范围内搜索元素“cd”的索引位置
-
//将Array转化成Set集合
-
Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
-
System.out.println(set);
-
//[d, e, b, c, a]
-
//数组翻转
-
int[] intArray = { 1, 2, 3, 4, 5 };
-
ArrayUtils.reverse(intArray);
-
System.out.println(Arrays.toString(intArray));
-
//[5, 4, 3, 2, 1]
-
//从数组中移除一个元素
-
int[] intArray = { 1, 2, 3, 4, 5 };
-
int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
-
System.out.println(Arrays.toString(removed));
-
//将一个int值转化成byte数组
-
byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();
-
for (byte t : bytes) {
-
System.out.format("0x%x ", t);
-
}
-
//检查数组中是否包含某一个值
-
String[] stringArray = { "a", "b", "c", "d", "e" };
-
boolean b = Arrays.asList(stringArray).contains("a");
-
System.out.println(b);
-
// true
-
//连接两个数组
-
int[] intArray = { 1, 2, 3, 4, 5 };
-
int[] intArray2 = { 6, 7, 8, 9, 10 };
-
// Apache Commons Lang library
-
int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
-
//将数组中的元素以字符串的形式输出
-
String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");
-
System.out.println(j);
3.3自定义类数组
class Person {...}
static Person [] aa = new Person [N];
for(int i = 0; i<N-1; i++){
aa [i] =Person ();
赋值操作;
}
即必须每个自定义类数组元素使用前都应该先初始化!
4.面向对象
4.1重载与重写
比较项目 | 重载 | 覆写/重写 |
英文名 | 超载 | 覆盖 |
函数签名 | 只要求函数的参数个数或类型不一致,对返回值没要求 | 函数的参数个数,类型,返回值都必须完全一样。 |
发生地方 | 同一个类或者具有继承关系的两个类中 | 只能发生在继承关系的两个类中 |
访问权限 | 没有限制
| 子类覆写方法的访问权限必须大于或等于父类的方法的访问权限 |
4.2单例模式
-
//饿汉(推荐)
-
public class demo {
-
public static void main(String[] args) {
-
test1 s = test1.get();
-
System.out.println(s);
-
}
-
}
-
class test1 {
-
private static test1 s = new test1();
-
public static test1 get() {
-
return s;
-
}
-
}
-
//懒汉
-
public class demo1 {
-
public static void main(String[] args) {
-
test2 s = test2.get();
-
System.out.println(s);
-
}
-
}
-
class test2 {
-
private static test2 s;
-
public static test2 get() {
-
if (s == null) {
-
s = new test2();
-
}
-
return s;
-
}
-
}
-
//懒汉式是延时加载, 懒汉式如果在创建实例对象时不加上synchronized则会导致对对象的访问不是线程安全的,
-
他是在需要的时候才创建对象,而饿汉式在虚拟机启动的时候就会创建。
4.3抽象类与接口
类抽象艺术的英文用来捕捉子类的通用特性的。它不能被实例化,只能被用作子类的超类。抽象类是被用来创建继承层级里子类的模板。
-
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
-
abstract void service(ServletRequest req, ServletResponse res);
-
}
-
//继承抽象类,实现抽象方法
-
public class HttpServlet extends GenericServlet {
-
void service(ServletRequest req, ServletResponse res) {
-
// implementation
-
}
-
}
接口的抽象艺术英文艺术方法的集合。如果一个类实现了某个接口,那么它就继承了这个接口的抽象方法。这就像契约模式,如果实现了这个接口,那么就必须确保使用这些方法接口。只是一种形式,接口自身不能做任何事情。
-
public interface Externalizable extends Serializable {
-
void writeExternal(ObjectOutput out) throws IOException;
-
void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
-
}
-
//继承并实现接口的方法
-
public class Employee implements Externalizable {
-
int employeeId;
-
String employeeName;
-
@Override
-
public void writeExternal(ObjectOutput out) throws IOException {
-
out.writeInt(employeeId);
-
out.writeObject(employeeName);
-
}
-
@Override
-
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
-
employeeId = in.readInt();
-
employeeName = (String) in.readObject();
-
}
-
}
什么时候使用抽象类和接口
-
如果你拥有一些方法并且想让它们中的一些有默认实现,那么使用抽象类吧。
-
如果你想实现多重继承,那么你必须使用接口。由于Java的的不支持多继承,子类不能够继承多个类,但可以实现多个接口。因此你就可以使用接口来解决它。
-
如果基本功能在不断改变,那么就需要使用抽象类。如果不断改变基本功能并且使用接口,那么就需要改变所有实现了该接口的类。
5.一些实用类
5.1String类及正则表达式
-
/**
-
* 1:输出字符串"HelloWorld"的字符串长度
-
* 2:输出"HelloWorld"中"o"的位置
-
* 3:输出"HelloWorld"中从下标5出开始第一次出现"o"的位置
-
* 4:截取"HelloWorld"中的"Hello"并输出
-
* 5:截取"HelloWorld"中的"World"并输出
-
* 6:将字符串" Hello "中两边的空白去除后输出
-
* 7:输出"HelloWorld"中第6个字符"W"
-
* 8:输出"HelloWorld"是否是以"h"开头和"ld"结尾的。
-
* 9:将"HelloWorld"分别转换为全大写和全小写并输出。
-
*/
-
public class Test01 {
-
public static void main(String[] args) {
-
String str = "HelloWorld";
-
test1(str);
-
}
-
public static void test1(String str){
-
System.out.println(str.length());
-
}
-
public static void test2(String str){
-
System.out.println(str.indexOf('o'));
-
}
-
public static void test3(String str){
-
System.out.println(str.indexOf('o', 5));
-
}
-
public static void test4(String str){
-
System.out.println(str.substring(0,5));//substring()内取右不取左
-
}
-
public static void test5(String str){
-
System.out.println(str.substring(5));
-
}
-
public static void test6(String str){
-
System.out.println(str.trim());
-
}
-
public static void test7(String str){
-
System.out.println(str.charAt(5));
-
}
-
public static void test8(String str){
-
System.out.println(str.startsWith("h")+"\n"+str.endsWith("ld"));
-
}
-
public static void test9(String str){
-
System.out.println(str.toLowerCase()+"\n"+str.toUpperCase());
-
}
-
}
正则表达式:
常见的正则表达式
[abc] abc中任意一个字符
[^abc] 除了abc的任意字符
[a-z] a-z中任意一个字符
[a-zA-Z0-9] a-z,A-Z,0-9中任意一个字符
[a-z&&[^bc]] 一个字符,a-z中除了bc意外的任意字符。
\d 任意一个数字字符 [0-9]
\D 任意一个非数字字符[^0-9]
\s 空白字符,[\t\n\r\x0B\f]
\S 非空白字符 [^\s]
\w 就是[a-zA-Z_0-9]
\W [^\w]
A? 表示0个或1个A
A* 表示0个或多个A
A+ 表示1个或多个A
A{5} 表示5个A
A{5,} 表示5个到任意多个A
A{5,11} 表示5个到11个A
-
1.从键盘输入一个手机号,判断手机号格式是否合法。
-
1) 全是数字
-
2) 11位
-
3) 1开头,第二位号码为345678,
-
static void function04() {
-
Scanner scan = new Scanner(System.in);
-
System.out.println("请输入用户手机号:");
-
String str = scan.next();
-
boolean b = str.matches("1[345678][0-9]{9}");
-
System.out.println(b?"号码正确!":"手机号有误!");10)
-
}
-
2.检查邮箱格式是否合法
-
1) @前 字母数字_ 至少1个
-
2) @后 字母数字 至少1个
-
3) 有形如.cn域名
-
实例:
-
//neo@sina.com
-
//huangliang@yaohoo.com.cn
-
static void function01(){
-
Scanner scan = new Scanner(System.in);
-
System.out.println("请输入你的邮箱地址:");
-
String email = scan.next();
-
boolean b = email.matches("[a-zA-Z_0-9]+@[a-z0-9]+(\\.[a-z]{2,})+");
-
System.out.println(b);
-
scan.close();
-
}
5.2Date类
-
//1.日期格式化输出
-
public static void name1() {
-
Date aaData = new Date();
-
DateFormat aa = new SimpleDateFormat("yyyy-MM-dd HH:mm");
-
String string = aa.format(aaData);
-
System.out.println(string);
-
}
-
//2018-07-19 21:35
-
//2.用户输入日期字符串,解析成Date 并打印。
-
public static void name2() {
-
System.out.println("请输入日期:如2018-07-18");
-
Scanner scanner = new Scanner(System.in);
-
String ss = scanner.nextLine().trim();
-
try {
-
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
-
Date date = format1.parse(ss);
-
System.out.println("Date:"+date);
-
String string = format1.format(date);
-
System.out.println("Date:"+string);
-
} catch (ParseException e) {
-
e.printStackTrace();
-
}
-
}
-
//键入2018-07-18
-
//Date:Wed Jul 18 00:00:00 CST 2018
-
//Date:2018-07-18
-
//3.计算你们在一起多少天了。
-
static void function06() throws Exception{
-
System.out.println("请你们认识的日期:如2018-07-18");
-
Scanner scan = new Scanner(System.in);
-
String str = scan.nextLine().trim();
-
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
-
Date date = format1.parse(str);//相遇日期
-
long t = date.getTime();
-
Date date1 = new Date();//当前日期
-
long t1 = date1.getTime();
-
long s = t1 - t;
-
long days = s/1000/60/60/24;
-
if(days<0) {
-
System.out.println("你的女票将在"+(-days)+"天后出现,请注意查收。");
-
}else {
-
System.out.println("你们已经认识"+days+"天。");
-
}
-
}
-
//today:2018-07-19
-
//键入2018-07-10
-
//你们已经认识9天。
5.3Calender类
-
//显示当前时间
-
public class Calendar_ {
-
public static void main(String[] args) {
-
function02();
-
}
-
static void function02(){
-
Calendar c = Calendar.getInstance();
-
System.out.println(c);
-
//显示设置的时间
-
//c.set(2099, 1, 9, 9, 9);
-
int year = c.get(Calendar.YEAR);
-
int month = c.get(Calendar.MONTH)+1;//month从0开始
-
int day = c.get(Calendar.DAY_OF_MONTH);
-
int hour = c.get(Calendar.HOUR_OF_DAY);
-
int m = c.get(Calendar.MINUTE);
-
System.out.println(year+"年"+month+"月"+day+"日"+hour+"点"+m+"分");
-
}
-
}
-
//2018年7月20日9点30分
5.4UUID类
-
// 生成一个id
-
public static String createId() {
-
UUID uid = UUID.randomUUID();
-
String userId = uid.toString();
-
String id = userId.replace("-", "");
-
return id;
-
}
-
//80e1146c3c7344dd9b957be907056c8f
6.集合
6.1List,Set以及Map比较
List:
- 可以允许重复的对象。
- 可以插入多个null元素。
- 是一个有序容器,保持了每个元素的插入顺序,输出的顺序就是插入的顺序。
- 常用的实现类有 ArrayList、LinkedList 和 Vector。ArrayList 最为流行,它提供了使用索引的随意访问,而 LinkedList 则对于经常需要从 List 中添加或删除元素的场合更为合适。
Set:
- 不允许重复对象
- 只允许一个 null 元素
- 无序容器,你无法保证每个元素的存储顺序,TreeSet通过 Comparator 或者 Comparable 维护了一个排序顺序。
- Set 接口最流行的几个实现类是 HashSet、LinkedHashSet 以及 TreeSet。最流行的是基于 HashMap 实现的 HashSet;TreeSet 还实现了 SortedSet 接口,因此 TreeSet 是一个根据其 compare() 和 compareTo() 的定义进行排序的有序容器
Map:
- Map不是collection的子接口或者实现类。Map是一个接口。
- Map 的 每个 Entry 都持有两个对象,一个键一个值(key,value),Map 可有相同的value但key必须是唯一的。
- TreeMap也通过Comparator或者Comparable维护了一个排序顺序。
- 地图里你可以拥有随意个空值但最多只能有一个空键键,。
- 5.Map接口最流行的几个实现类是HashMap,LinkedHashMap,Hashtable和TreeMap。(HashMap,TreeMap最常用)
6.2不同场景下的使用情况
- 如果你经常使用索引查找,用ArrayList。如果经常添加删除元素,用LinkedList。
- 如果你想容器中的元素有序存储,那么List。
- 如果你不想有重复值的出现,选择Set的实现类,所有存储于TreeSet中的元素可以使用Java里的比较器或者Comparable进行排序.LinkedHashSet的遍历序和插入序是一致。
- 如果你以键和值的形式进行数据存储那么Map。
7.IO基本操作
7.1字节流与字符流的区别
- 字节流操作的基本单元为字节;字符流操作的基本单元为Unicode的的码元。
- 字节流默认不使用缓冲区;字符流使用缓冲区。
- 字节流通常用于处理二进制数据,实际上它可以处理任意类型的数据,但它不支持直接写入或读取的Unicode的码元;字符流通常处理文本数据,它支持写入及读取的Unicode的码元。
那开发中究竟用字节流好还是用字符流好呢?
一般选择字节流
字符流操作文本,其他的字节流。
7.2字节流与字符流的实例
-
//字节流写入"好好学习Java"到.txt
-
public class WriteIntoTXT {
-
public static void main(String[] args) {
-
FileOutputStream fos = null;
-
try {
-
String str = "好好学习Java";
-
byte[] words = str.getBytes();
-
fos = new FileOutputStream("D:\\Project resources\\Java_File_txt\\hello.txt");
-
fos.write(words, 0, words.length);
-
System.out.println("hello文件已更新!");
-
} catch (IOException obj) {
-
System.out.println("创建文件时出错!");
-
} finally {
-
try {
-
if (fos != null){
-
fos.close();
-
}
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
}
-
/**
-
* 字符流
-
* 文件数据读写
-
1) 在硬盘上创建一个文件
-
2) 一个方法写入 20 个 byte, 整数: 1, 2, ... 20
-
3) 定义一个方法逐个 byte 读取内容, 并且累加全部的结果,返回
-
*/
-
public class FileToAry {
-
static int sum = 0;
-
public static void main(String[] args) throws Exception {
-
FileWriter fiss = null;
-
FileWriter fisss = null;
-
BufferedReader br = null;
-
try {
-
int[] ary = null;
-
byte[] num = new byte[20];
-
fisss = new FileWriter("D:\\Project resources\\Java_File_txt\\1`20.txt");
-
fiss = new FileWriter("D:\\Project resources\\Java_File_txt\\1加到20的和.txt");
-
// 使用BufferedReader最大好处是可以按行读取,每次读取一行
-
br = new BufferedReader(new FileReader("D:\\Project resources\\Java_File_txt\\1`20.txt"));
-
String temp;// 定义字符串,用于保存每行读取到的数据
-
for (int i = 0; i < 20; i++) {
-
num[i] = (byte) (i + 1);
-
System.out.println(num[i]);
-
}
-
for (int i = 0; i < 20; i++)
-
fisss.write(String.valueOf(num[i]) + "\t");
-
fisss.flush();
-
while ((temp = br.readLine()) != null) {
-
ary = aryChange(temp);// 通过函数把字符串数组解析成整数数组
-
}
-
for (int i = 0; i < 19; i++) {
-
fiss.write(String.valueOf(ary[i]) + "+");
-
}
-
fiss.write(String.valueOf(ary[19]) + "=");
-
fiss.write(String.valueOf(sum));
-
fiss.flush();
-
} catch (IOException obj) {
-
System.out.println("文件出错!");
-
} finally {
-
try {
-
br.close();// 关闭输入流
-
fiss.close();
-
fisss.close();
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
}
-
static int[] aryChange(String temp) {// 字符串数组解析成int数组
-
String[] ss = temp.trim().split("\t");// .trim()可以去掉首尾多余的空格
-
int[] ary = new int[ss.length];
-
for (int i = 0; i < ss.length; i++) {
-
ary[i] = Integer.parseInt(ss[i]);// 解析数组的每一个元素
-
sum += ary[i];
-
}
-
return ary;// 返回一个int数组
-
}
-
}
-
//1+2+3+4+5+6+7+8+9+10+11+12+13+14+15+16+17+18+19+20=210