这可以返回一个整数列表:
public List<Integer> GetIListImpl() {
return new ArrayList<Integer>();
}
但是如果我想让调用者指定泛型呢?像这样的东西,虽然在语法上我不确定该怎么做:
public List<T> GetIListImpl<T>() {
return new ArrayList<T>();
}
用法是:
List<String> = GetIListImpl<String>();
最佳答案
static参数化类型的工厂方法看起来您想编写方便的工厂方法来实例化泛型集合。
你可以写这样的通用方法:
public static <T> List<T> newArrayList() {
return new ArrayList<T>();
}
public static <K,V> Map<K,V> newHashMap() {
return new HashMap<K,V>();
}
然后你可以简单地写:
// absolutely type-safe!!! no compilation warnings at all!!!
List<String> names = newArrayList();
List<Integer> nums = newArrayList();
Map<String, List<String>> map = newHashMap();
请注意,在某些情况下,上述方法不一定是 static ,您可以选择省略实现 class从方法中命名并仅使用 interface名称(例如 newList 、 newMap )。
这种泛型类型推断 static工厂方法实际上得到了 Effective Java 2nd Edition 的认可;它有幸成为书中讨论的第一个项目。
以下是第 1 项的相关引述:考虑 static工厂方法而不是构造函数:
A fourth advantage of
staticfactory methods is that they reduce the verbosity of creating parameterized type instances.When you invoke the constructor of a parameterized class, unfortunately you must specify the type parameters even if they're obvious from context. This typically requires you to provide the type parameters twice in quick succession:
Map<String,List<String>> m = new HashMap<String,List<String>>();This redundant specification quickly becomes painful as the length and complexity of the type parameters increase. With
staticfactories, however, the compiler can figure out the type parameters for you. This is known as type inference. For example, suppose thatHashMapprovided thisstaticfactory:public static <K,V> HashMap<K,V> newInstance() { return new HashMap<K,V>(); }Then you could replace the wordy declaration above with this succinct alternative:
Map<String,List<String>> m = HashMap.newInstance();Unfortunately the standard collection implementations such as
HashMapdo not havestaticfactory methods as of release 1.6, but you can put these methods in your own utility class. More importantly you can provide suchstaticfactories in your own parameterized classes.
该项目还规定了这些 static 的通用命名约定工厂方法:
getInstance- returns an instance that is described by the parameters […]newInstance- LikegetInstance, except it guarantees that each instance returned is distinct from all others.newType- LikenewInstance, but used when the factory method is in a different class.Typeindicates the type of object returned by the factory method.
在大多数情况下,您不必显式提供类型参数,因为 Java 泛型类型推理系统通常可以找出您需要什么。
然而,要提供显式类型参数,语法是将其放在方法名称之前(而不是之后)。这是一个使用显式参数调用泛型方法 <T> List<T> emptyList() 的示例来自 java.util.Collections :
Collections.<String>emptyList();
// Collections.emptyList<String>(); // DOES NOT COMPILE
请注意,泛型方法调用的显式类型参数化的语法怪癖是您必须限定类型(如果 static )或您调用该方法的对象,甚至如果不是显式参数化,它们是否可以省略。
需要注意的是Guava事实上已经提供了static Java Collections Framework 中类型的工厂方法:
来自主 package com.google.common.collect :
Lists.newArrayList() , newLinkedList() , ……Sets.newHashSet() , newTreeSet() , newEnumSet(…) , ……Maps.newHashMap() , newTreeMap() , newEnumMap(…) , ……事实上,本着Effective Java 2nd Edition推荐的精神,Guava自己的集合不提供public构造函数,而是提供 static create()工厂方法:
HashMultiSet.create() , 一个 Multiset 实现TreeMultimap.create() , 一个 Multimap 实现库的其余部分还提供了许多非常有用的功能。
关于Java:泛型语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3542139/
我脑子里浮现出一些关于一种新编程语言的想法,所以我想我会尝试实现它。一位friend建议我尝试使用Treetop(Rubygem)来创建一个解析器。Treetop的文档很少,我以前从未做过这种事情。我的解析器表现得好像有一个无限循环,但没有堆栈跟踪;事实证明很难追踪到。有人可以指出入门级解析/AST指南的方向吗?我真的需要一些列出规则、常见用法等的东西来使用像Treetop这样的工具。我的语法分析器在GitHub上,以防有人希望帮助我改进它。class{initialize=lambda(name){receiver.name=name}greet=lambda{IO.puts("He
所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
在Ruby类中,我重写了三个方法,并且在每个方法中,我基本上做同样的事情:classExampleClassdefconfirmation_required?is_allowed&&superenddefpostpone_email_change?is_allowed&&superenddefreconfirmation_required?is_allowed&&superendend有更简洁的语法吗?如何缩短代码? 最佳答案 如何使用别名?classExampleClassdefconfirmation_required?is_a
可能已经问过了,但我找不到它。这里有2个常见的情况(对我来说,在编程Rails时......)用ruby编写是令人沮丧的:"astring".match(/abc(.+)abc/)[1]在这种情况下,我得到一个错误,因为字符串不匹配,因此在nil上调用[]运算符。我想找到的是比以下内容更好的替代方法:temp="astring".match(/abc(.+)abc/);temp.nil??nil:temp[1]简而言之,如果不匹配,则简单地返回nil而不会出错第二种情况是这样的:var=something.very.long.and.tedious.to.writevar=some
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我正在学习Ruby的基础知识(刚刚开始),我遇到了Hash.[]method.它被引入a=["foo",1,"bar",2]=>["foo",1,"bar",2]Hash[*a]=>{"foo"=>1,"bar"=>2}稍加思索,我发现Hash[*a]等同于Hash.[](*a)或Hash.[]*一个。我的问题是为什么会这样。是什么让您将*a放在方括号内,是否有某种规则可以在何时何地使用“it”?编辑:我的措辞似乎造成了一些困惑。我不是在问数组扩展。我明白了。我的问题基本上是:如果[]是方法名称,为什么可以将参数放在括号内?这看起来几乎——但不完全是——就像说如果你有一个方法Foo.d
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/