hhh*_*hhh 1 java types data-structures
术语过度类型结构=接受不同类型的数据结构,可以是原始的或用户定义的.
我认为ruby在诸如表之类的结构中支持许多类型.我在Java中尝试了一个类型为'String','char'和'File'的表但是错误.
如何在声明中显示类型?在启动时怎么样?假设一个结构:
INDEX VAR FILETYPE
//0 -> file FILE
//1 -> lineMap SizeSequence
//2 -> type char
//3 -> binary boolean
//4 -> name String
//5 -> path String
Run Code Online (Sandbox Code Playgroud)码
import java.io.*;
import java.util.*;
public class Object
{
public static void print(char a)
{
System.out.println(a);
}
public static void print(String s)
{
System.out.println(s);
}
public static void main(String[] args)
{
Object[] d = new Object[6];
d[0] = new File(".");
d[2] = 'T';
d[4] = ".";
print(d[2]);
print(d[4]);
}
}
Run Code Online (Sandbox Code Playgroud)
错误
Object.java:18: incompatible types
found : java.io.File
required: Object
d[0] = new File(".");
^
Object.java:19: incompatible types
found : char
required: Object
d[2] = 'T';
^
Run Code Online (Sandbox Code Playgroud)
在对真正的问题造成滋扰之后:
d [2]存储char-type,但方法将其视为Object.我的许多方法都没有Object,所以因为这个而改变它们感觉太多了.
码
package file;
import java.io.*;
import java.util.*;
public class ObjectTest
{
//I have this kind of methods
//I want them to work with Object
// without changing the par type,
// possible?
public static void print(char a)
{
System.out.println(a);
}
public static void print(String s)
{
System.out.println(s);
}
public static void main(String[] args)
{
java.lang.Object[] d = new java.lang.Object[6];
d[0] = (Object) new File(".");
d[2] = (Object) new Character('T');
d[4] = (Object) new String(".");
print(d[2]);
print(d[4]);
}
//I can get it this way working
// but some of my methods are not Objects
// and they need to be types like String
private static void print(Object object) {
System.out.println(object);
}
}
Run Code Online (Sandbox Code Playgroud)
您已将您的类命名为Object,因此它与java.lang.Object冲突.给它另一个名称,或者在数组声明中包含包名.例如
java.lang.Object[] d = new java.lang.Object[6];
Run Code Online (Sandbox Code Playgroud)