我刚刚开始学习java,我有两个基本问题.我的main()看起来像这样:
public class Main {
public static void main(String[] args) {
Storage<BankAccount> aStorage = new Storage<BankAccount>();
Storage<String> sStorage = new Storage<String>();
Class baCls = BankAccount.class;
try {
Object myAccount = baCls.newInstance();
aStorage.setValue( myAccount );
myAccount.deposit( 15 );
}
catch ( InstantiationException e ) {
}
catch ( IllegalAccessException e ) {
}
}}
Run Code Online (Sandbox Code Playgroud)
为什么我会收到这些错误:
之后我试图替换:
Object myAccount = baCls.newInstance();
Run Code Online (Sandbox Code Playgroud)
同
BankAccount myAccount = baCls.newInstance();
Run Code Online (Sandbox Code Playgroud)
但后来我收到了这个错误:
我知道正确的方法是:
BankAccount myAccount = (BankAccount) baCls.newInstance();
Run Code Online (Sandbox Code Playgroud)
但我不确定我理解为什么......我试图从各种来源阅读它,所以我有一些理论,但我仍然无法正确地理解这一点.有人可以帮我理解吗?
PS很抱歉发布这样一个基本问题.
我正在寻找有关矢量迭代的一些提示.我正在尝试完成一个挑战,你必须实现一个函数(SumOfTwo),它接受两个向量和一个和作为参数,并且必须检查两个向量中是否有任何数字对,如果添加可以给出总和作为参数传递.
我的功能很好,除了它不包括500毫秒的时间限制.我觉得有一个更好的方法来迭代两个向量而不是两个for循环,但我觉得非常卡住......
bool sumOfTwo(std::vector<int> a, std::vector<int> b, int v) {
if((a.empty()) || b.empty()){
return false;
}
for (std::vector<int>::iterator it1 = a.begin(); it1<=a.end(); ++it1) {
for (std::vector<int>::iterator it2 = b.begin(); it2<=b.end(); ++it2) {
if ((*it1 + *it2) == v){
return true;
}
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)