文章目录
1. 前言
创作开始时间:2021年11月8日21:48:25
写java很久了,感觉经常会反复用到一些代码,有时候记不住,所以在这里写一个cheatsheet,记录一些常用的操作。
泛型 generic type
Map的key是不能用泛型的,value可以!
- Java Generic Map with Generic Type as key/ values https://stackoverflow.com/questions/30895435/java-generic-map-with-generic-type-as-key-values
- Java generics: Declare map value of generic type https://stackoverflow.com/questions/11012989/java-generics-declare-map-value-of-generic-type/11013073
日志处理
- log4j - PatternLayout https://www.tutorialspoint.com/log4j/log4j_patternlayout.htm
- log4j2: Abbreviate / shorten package names https://stackoverflow.com/questions/38272287/log4j2-abbreviate-shorten-package-names
- RollingFile Appender Log4j2 not printing Line number https://stackoverflow.com/questions/32121664/rollingfile-appender-log4j2-not-printing-line-number
接口和抽象类
interface的成员变量:
- 再学Java 之 interface的成员变量 https://www.cnblogs.com/scutwang/p/4120749.html
此外:
- Java基础之接口与抽象类的区别 https://zhuanlan.zhihu.com/p/94770324
类(面向对象)
List getter setter
可以直接赋值。也可以addAll。看具体场景了。
2. 相似度的相关操作
参考:
- Similarity String Comparison in Java https://stackoverflow.com/questions/955110/similarity-string-comparison-in-java
- https://github.com/Simmetrics/simmetrics 这个repo感觉还不错的。
3. 数据结构
3.1. tree的实现!
具体代码在我的mcstudy项目。
- How to implement a tree data-structure in Java? https://stackoverflow.com/questions/3522454/how-to-implement-a-tree-data-structure-in-java 这里的参考还可以,进一步给出了下面的参考
- gt4dev/yet-another-tree-structure https://github.com/gt4dev/yet-another-tree-structure/tree/master/java/src/com/tree 这里有具体的tree实现
3.2. 图的实现
具体代码在我的mcstudy项目。
参考:
- Graphs in Java https://www.baeldung.com/java-graphs 主要参考
其他:
- https://www.softwaretestinghelp.com/java-graph-tutorial/
- https://www.geeksforgeeks.org/graph-and-its-representations/
- In a tree, can a child has multiple parents? https://stackoverflow.com/questions/65504660/in-a-tree-can-a-child-has-multiple-parents
4. org.eclipse.jdt.core.dom 包的操作
4.1. typebinding
参考:
- Convert Eclipse JDT ITypeBinding to a Type https://stackoverflow.com/questions/11091791/convert-eclipse-jdt-itypebinding-to-a-type
5. eclipse神技
5.1. 批量插入getter 和 setter
之前太懒了,没来得及研究,今天才发现可以批量选择性插入getter和setter,很方便。
大概是:在编辑界面,右键source,然后就有generate getter setter的选项了!
- Is there a way to automatically generate getters and setters in Eclipse? https://stackoverflow.com/questions/7221691/is-there-a-way-to-automatically-generate-getters-and-setters-in-eclipse
5.2. 安装ast view 插件
很方便,直接参考下面官网,下载jar后放到dropins 文件夹就行,(也可以在eclipse的marketplace下载,但是网速太慢了)。
- org.eclipse.jdt.astview - AST View https://www.eclipse.org/jdt/ui/astview/index.php
5.3. 自动代码补全
之前只有.可以补全,现在设置过后全部都可以补全了,还挺好的。
- Auto code completion on Eclipse https://stackoverflow.com/questions/6202223/auto-code-completion-on-eclipse
5.4. 出现红色感叹号咋办?
Decorates Java projects and working sets that contain build path errors
我的是maven项目,需要:
1)根据problems的提示,解决build path的错误依赖问题。(比如依赖不存在)
2)然后右键pom.xml,update project,就好啦!
- What does the red exclamation point icon in Eclipse mean? https://stackoverflow.com/questions/5640823/what-does-the-red-exclamation-point-icon-in-eclipse-mean
6. 运算符
6.1. Java运算符优先级
单目乘除为关系,逻辑三目后赋值。
单目:单目运算符+ –(负数) ++ – 等
乘除:算数单目运算符* / % + -
为:位移单目运算符<< >>
关系:关系单目运算符> < >= <= == !=
逻辑:逻辑单目运算符&& || & | ^
三目:三目单目运算符A > B ? X : Y
后:无意义,仅仅为了凑字数
赋值:赋值=
7. equals 和 hashcode方法
7.1. equals override实例
@Override
public boolean equals(Object obj) {
// self check
if (this == obj) {
return true;
}else if (obj == null) { //null check
return false;
}else if (getClass() != obj.getClass()) { // type check
return false;
}else {
xxx fsOther = (xxx) obj; // cast
// compare
return xxx ;
// return Objects.equals(this.data, fsOther.data);
}
}
- How to Implement Java’s equals Method Correctly https://www.sitepoint.com/implement-javas-equals-method-correctly/
7.2. 使用场景
从Jdk源码的注释中可以看出,hashCode() 在散列表中才会发挥作用,当对象无需创建像HashMap、HashSet等集合时,可以不用重写hashCode方法,但是如果有使用到对象的哈希集合等操作时,必须重写hashCode()和equals()。
- Java中equals()和HashCode()的关系 https://blog.csdn.net/qq_33619378/article/details/92661494
8. 下载org.eclipse.jdt.core源码
方法一:
访问官网:https://git.eclipse.org/r/plugins/gitiles/jdt/eclipse.jdt.core/+/BETA_JAVA13/org.eclipse.jdt.core下载tar.gz,或者用wget:
wget [https://git.eclipse.org/r/plugins/gitiles/jdt/eclipse.jdt.core/+archive/BETA_JAVA13/org.eclipse.jdt.core.tar.gz](https://git.eclipse.org/r/plugins/gitiles/jdt/eclipse.jdt.core/+archive/BETA_JAVA13/org.eclipse.jdt.core.tar.gz)
方法二:
在网址:https://git.eclipse.org/r/plugins/gitiles/jdt/eclipse.jdt.core/+refs 寻找合适的版本,因为我目前用到的是3.26版本的jar包。所以我想找到对应的源码。
方法三:
刚刚才发现,直接在我本地的maven repository文件夹下面就有源码!
/home/apr/.m2/repository/org/eclipse/jdt/org.eclipse.jdt.core/3.26.0/org.eclipse.jdt.core-3.26.0-sources.jar
直接解压就行了,挺快的。
9. 路径操作
9.1. 转为绝对路径(不带… 的那种)
new File(".").getCanonicalPath()
- Get file full path in java https://stackoverflow.com/questions/2981972/get-file-full-path-in-java/43550717
9.2. 使用泛型
public <T> List<T> magicalListGetter() {
return new ArrayList<T>();
}
// 我写的函数:
public static <T> void printList(List<T> list) {
int i = 0;
for (T t : list) {
System.out.format("[%s] %s\n", i++, t.toString());
}
if (list.isEmpty()) {
System.out.format("Empty List.\n\n");
}else {
System.out.format("\n");
}
}
- How to have Java method return generic list of any type? https://stackoverflow.com/questions/17840483/how-to-have-java-method-return-generic-list-of-any-type/17840541
10. 列表
10.1. string arrays转list
# 得到的list不可修改,即不可以添加或者删除元素
List<String> strings = Arrays.asList(new String[]{"one", "two", "three"});
# 得到的list可修改,即可以添加或者删除元素
List<String> strings =
new ArrayList<String>(Arrays.asList(new String[]{"one", "two", "three"}));
参考:
- Converting String array to java.util.List https://stackoverflow.com/questions/6026813/converting-string-array-to-java-util-list/6026854
10.2. list转string array
// jdk11
String[] array = yourList.toArray(String[]::new);
// jdk8
String[] array= yourList.stream().toArray(String[]::new);
参考:
- Convert list to array in Java [duplicate] https://stackoverflow.com/questions/9572795/convert-list-to-array-in-java
10.3. 截取top-n个元素
// 方法1
list.subList(100, list.size()).clear();
// 方法2
list = list.subList(0, 100);
- Truncate a list to a given number of elements https://stackoverflow.com/questions/1279476/truncate-a-list-to-a-given-number-of-elements
ArrayList的初始化
return new ArrayList<String>(Arrays.asList(singleElement));
- How to quickly and conveniently create a one element arraylist [duplicate] https://stackoverflow.com/questions/20358883/how-to-quickly-and-conveniently-create-a-one-element-arraylist
Array初始化
# 方法1
Globals.inclusionFilter = { "AbstractXYItemRenderer", "AbstractCategoryItemRenderer" };
# 方法2
Globals.inclusionFilter;
Globals.inclusionFilter = new String[] { "AbstractXYItemRenderer", "AbstractCategoryItemRenderer" };
- Why can array constants only be used in initializers? [duplicate] https://stackoverflow.com/questions/10520617/why-can-array-constants-only-be-used-in-initializers
11. 字符串操作
11.1. 正则表达式
11.1.1. 基础语法!(基础)
11.1.2. 将一个java文件里面的所有word单词替换为ID
A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore(_) or a dollar sign ($). for example, @javatpoint is not a valid identifier because it contains a special character which is @.
// A-Za-z0-9_\\$ 包含所有identifier的组成元素。
String fomattedContent = content.replaceAll("[A-Za-z0-9_\\$]+", "ID");
- Identifiers in Java https://www.javatpoint.com/identifiers-in-java
- Replace all words with another string with Java Regular Expressions https://www.tutorialspoint.com/replace-all-words-with-another-string-with-java-regular-expressions
- Java (Regex) - Get all words in a sentence https://stackoverflow.com/questions/14539484/java-regex-get-all-words-in-a-sentence
11.2. split 多个空格
String[] argArray = arg.split("\\s+");
参考:
- Splitting string on multiple spaces in java [duplicate] https://stackoverflow.com/questions/13081527/splitting-string-on-multiple-spaces-in-java
split大写字母(拆分java里面的变量名)
String[] camelCaseWords = s.split("(?=[A-Z])");
- Java: Split string when an uppercase letter is found https://stackoverflow.com/questions/3752636/java-split-string-when-an-uppercase-letter-is-found
11.3. 替换多个空格为一个空格
# 方法1
String after = before.trim().replaceAll(" +", " ");
# 方法2
sValue = sValue.trim().replaceAll("\\s+", " ")
- Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces https://stackoverflow.com/questions/2932392/java-how-to-replace-2-or-more-spaces-with-single-space-in-string-and-delete-lead
- What does regular expression \s*,\s* do? https://stackoverflow.com/questions/13750716/what-does-regular-expression-s-s-do
String.format的转义
% 的转义
如下:
String cmd = String.format("cd %s; git log --pretty=format:\"%H\" > %s", repoDir, commitIdPath);
这样是错的,正确的写法是:
# 必须在%前面加上%,才能转义!
String cmd = String.format("cd %s; git log --pretty=format:\"%%H\" > %s", repoDir, commitIdPath);
- java特殊处理String.format中的%,使用%做一次转义 https://www.cnblogs.com/meitian/p/14327246.html
12. Map
12.1. 初始化
理论上,key可以是任何类型。
从HashMap的语法上来讲,一切对象都可以作为Key值。如:Integer、Long、String、Object等。但是在实际工作中,最常用的使用String作为Key值。
但是推荐:key的类型最好是string类型。
参考:
- HashMap 中 Key 类型的选择 https://www.cnblogs.com/lihao007/p/12444193.html
12.2. 遍历
4种方法:
Map<String,String> map = new HashMap<String,String>();
map.put("a", "aa")
map.put("b", "bb")
map.put("b", "cc")
// 1 Entry
for (Map.Entry<String,String> entry : map .entrySet())
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
// 2 keySet()
for (String key: map.keySet())
System.out.println("key: " + key);
for (String value : map.values())
System.out.println("value: " + value );
// 3 使用iterator
Iterator<Map.Entry<String, String>> itr = map.entrySet().iterator();
while(itr.hasNext())
{
Map.Entry<String, String> entry = itr.next();
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
}
// 4 java8才开始支持foreach
map.forEach((k,v) -> System.out.println("Key = "
+ k + ", Value = " + v));
参考:
- How to iterate any Map in Java https://www.geeksforgeeks.org/iterate-map-java/
13. 其他
13.1. switch语句
13.2. 枚举enum
- Java Enums tutorials.jenkov.com/java/enums.html
set 和 list的相互转换
// list to set
Set<Integer> targetSet = new HashSet<>(sourceList);
// set to list
List<Integer> targetList = new ArrayList<>(sourceSet);
- Converting Between a List and a Set in Java https://www.baeldung.com/convert-list-to-set-and-set-to-list
14. 小结
创作结束时间: