JAVA variable as 2 types

Java变量为2种类型

问题 (Question)

How can I create value of type String and also Collection?

I want someTimes put in this Strings and the othertimes put collections.

EDIT:

I found Solution: I created an interface and declear this Objects as this interface.

我怎样创建字符串类型和收藏价值?

我想有时放在这个字符串和其他把收藏。

编辑

我找到了解决办法:我创建了一个接口,把这个对象作为接口。

最佳答案 (Best Answer)

You cant. String is a final class, meaning you cannot extend upon it. A String will only ever be a String. You can have a collections that contain Strings, but a String object will only have 2 types: Object and String.

You can have a class that contains a String (or a StringBuilder) and a collection, then use that class to store/receive from

你不行。字符串是一个最终类,意味着你不能延伸到。一个字符串,将永远是一个只有字符串。你可以有一个集合,包含字符串,但一个string对象,只会有2种类型:对象和字符串。

你可以有一个类包含一个字符串(或StringBuilder)和收集,然后使用该类存储/接收

答案 (Answer) 2

Java does not support union types; however, both of these types share the same base Object class, so you could assign either one of them to a variable defined like this

 Object something;
 something = "Hello World!";
 something = new ArrayList(); // this is a collection.

Odds are that you probably were thinking of a Collection of Strings, in which case, you define it like Collection<String>

 Collection<String> strings = new ArrayList<String>();
 strings.add("Hello");
 strings.add("World");
 strings.add("!");

If that's not what you wanted, and you really want to sometimes store a String and sometimes store a Collection, remember that Java enforces strict type checking. This means that variables cannot just store anything, they must store something that is type compatible.

String and Collection are too different to be considered type compatible without some seriously bad programming (like using Object) or something even stranger.

Java不支持联盟的类型;然而,这两种类型共享相同的基础Object类,你可以指定其中一个来定义这样的变量

 Object something;
 something = "Hello World!";
 something = new ArrayList(); // this is a collection.

赔率是,你可能正在考虑一个字符串的集合,在这种情况下,你如何定义它像Collection<String>

 Collection<String> strings = new ArrayList<String>();
 strings.add("Hello");
 strings.add("World");
 strings.add("!");

如果这不是你想要什么,你真的想有时存储字符串有时商店收集,记住,Java强制执行严格的类型检查。这意味着变量不能存储任何东西,他们必须存储的东西类型兼容

StringCollection被认为是没有一些严重的编程类型兼容也不同(如使用Object)或者甚至陌生人。

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/23451903