Java 作为LinkedList或HashSet的类是否被视为依赖项?
最近我听说了依赖项注入,我很想知道像Java中的LinkedList这样的类,还是其他Java本机类被认为是依赖项 假设我有一个方法,将一个字符串数组解析为一组字符串 首先,我从一个数组生成一个集合对象——在本例中是链表——然后将其转换为哈希集 那么,HashSet和LinkedList都被视为依赖项吗Java 作为LinkedList或HashSet的类是否被视为依赖项?,java,dependency-injection,dependencies,Java,Dependency Injection,Dependencies,最近我听说了依赖项注入,我很想知道像Java中的LinkedList这样的类,还是其他Java本机类被认为是依赖项 假设我有一个方法,将一个字符串数组解析为一组字符串 首先,我从一个数组生成一个集合对象——在本例中是链表——然后将其转换为哈希集 那么,HashSet和LinkedList都被视为依赖项吗 private Set<String> foo(String[] strs){ LinkedList<String> listOfStrings = new Li
private Set<String> foo(String[] strs){
LinkedList<String> listOfStrings = new LinkedList<String>(Arrays.asList(strs));
Set<String> setOfStrings = new HashSet<String>();
for(String s: listOfStrings){
setOfStrings.add(s);
}
return setOfStrings;
}
private Set foo(String[]strs){
LinkedList listOfStrings=新的LinkedList(Arrays.asList(strs));
Set setOfstring=new HashSet();
对于(字符串s:ListOfstring){
集合字符串。添加(s);
}
返回序列集;
}
在示例代码中,HashSet和LinkedList并不完全是依赖项,因为它们属于
这里是该方法的内部实现
如果您可能有一个方法,该方法可以将集合作为参数,您可以将任何类型的集合作为依赖项提供给它,那么它可以被称为DI
public void doSomeAction(Collection<String>) { // Here, any type of Collection can be supplied by the caller, essentially making it a dependency which you can inject for example during Unit Testing..
.......// some code
}
public void doSomeAction(Collection){//在这里,调用方可以提供任何类型的集合,本质上使它成为一个依赖项,您可以在单元测试期间注入它。。
……一些代码
}
如果您想提供一些依赖注入,可以执行以下操作
static <T> Set<T> setOf(T... strs){
return setWith(new HashSet<>(), strs);
}
// pass in the set to populate
static <T> Set<T> setWith(Set<T> set, T... strs) {
Collections.addAll(set, strs);
return set;
}
静态设置(T…strs){
返回setWith(newhashset(),strs);
}
//传入要填充的集合
静态集合集合(集合集合,T…strs){
集合。添加所有(集合,strs);
返回集;
}
你可以以后再做
// uses a sorted set
Set<String> words = setWith(new TreeSet<>(), "hello", "world");
//使用排序集
Set words=setWith(new TreeSet(),“hello”,“world”);
我同意赫尔伍德的观点-
是的,它们在技术上是依赖性的,但是不,您不需要从依赖性注入的角度来担心它们
使用依赖项注入是为了在不更改方法中的代码(通常用于单元测试)的情况下,用不同的类替换底层类。对于“本机java类”,通常不需要交换它们,因此通常不需要为它们使用依赖项注入。它们在技术上可能是依赖项,但就依赖项注入而言,可能不值得为它们担心,除非您预见到需要在不更改其代码的情况下向该方法中注入不同容器类型的场景。有趣的依赖项是您将来可能需要更改的。顺便说一句,在本例中,您不需要
LinkedList
,您可以使用集合。addAll
而不是Arrays.asLIst
您只需要返回的集合,甚至可以为您填充。从技术上讲,如果您要将外部配置文件或系统属性中的多个值传递给应用程序,您可以将它们作为collection
或Map
@Steve插入,如果我正在进行单元测试,我只关注输入和输出,而不是方法内部发生的事情。