boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 问一个java的函数调用问题
相关主题
关于leetcode上那个买卖股票II的问题
Best Time to Buy and Sell Stock II这么简单?
[solved]stock这题目我 自己调试没问题,为什么leetcode总过不去
string permutation,怎么处理重复字母?
Best Time to Buy and Sell Stock 出三了。。。
Leetcode 上面的 Best Time to Buy and Sell Stock III
做了一下 Google 的 Best Time to Buy and Sell Stock II
贴个自己的答案:Binary Tree Max Path Sum
Yodle 面试题 Triangle 答对能有面试机会
我也遇到leetcode上Run Time Error,但在自己的机子能通过
相关话题的讨论汇总
话题: solution话题: prices话题: minvalue话题: maxdiff话题: int
进入JobHunting版参与讨论
1 (共1页)
s**********4
发帖数: 3
1
会写c++,只是拿leetcode一个例子来问一下java的函数调用问题:
比如说我现在创建了两个文件:Solution.java和SolutionTest.java:
Solution.java:
public class Solution {
public int maxProfit(int[] prices) {
// Start typing your Java solution below
// DO NOT write main() function
if (prices.length < 2)
return 0;
int maxDiff = 0;
int minValue = prices[0];
for (int i = 1; i < prices.length; ++i) {
if (prices[i] < minValue)
minValue = prices[i];
if (prices[i] - minValue > maxDiff)
maxDiff = prices[i] - minValue;
}
return maxDiff;
}
}
SolutionTest.java:
public class SolutionTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution solution = new Solution(); // create a new object
int[] prices = {-1, 1, 2};
System.out.println("Maximum profit is " + solution.maxProfit(prices)
);
}
}
程序可以通过。我的问题是,这样写是不是一种professional的方法?
就是先Solution solution = new Solution();
然后调用solution.maxProfit(prices)
总觉得这个maxProfit函数其实可以是static的。如果我刚才的那个方法不是
professional的方法,怎么改比较好?
非常感谢! :)
z****e
发帖数: 54598
2
什么方法不能写成static的?
用古德霸的话说就是
当你把全部的东西都static了之后
就跟c很像了
static和对象方法的区别在于
一般情况下,只有工具类会被static
最常见的也就是util结尾的类的方法会被static起来
其它一概都是跟对象绑定
你把方法写成static主要是为了不new那一个对象
以节省memory吧?
那在server side,有专门的framework帮你节省memory
比如spring,所以也不需要你刻意去搞成static
也就是说只有系统层面的方法才需要你去static
这个层级很高,一般来说,除了util,其它的没有必要static
z****e
发帖数: 54598
3
professional的写法
如果是core java
Solution s = SolutionBuilder.build();
如果是j2ee
@Autowire
Solution s;
@Inject
Solution s;
@Validate
Solution s;
等等等等,写法很多,看具体情况具体分析,跟使用的framework也有关系
f*******t
发帖数: 7549
4
A家用spring + junit
test class里主要内容如下:
@Autowrire
Solution s;
@Test
public void testMaxProfit() {
int[] prices = ...
int result = s.maxProfit(prices);
AssertEqual(result, ...);
}
l**b
发帖数: 457
5
一看就ID啊。。。。太恐怖了啊。。。。ID在dynamic lang里面debug起来挺头晕的。
l**b
发帖数: 457
6
一看就DI啊。。。。太恐怖了啊。。。。DI在dynamic lang里面debug起来挺头晕的。
1 (共1页)
进入JobHunting版参与讨论
相关主题
我也遇到leetcode上Run Time Error,但在自己的机子能通过
请教一个DP解法
有个很简单的程序但是有segmentation fault是问啥
java concurrence 例子
请问为什么这个程序会出现RunTime Error
Best Time to Buy and Sell Stock III怎么能证明或者保证两个区间没有相交?
网上很多blog show算法结果是个错的作者压根没验证过
问道OOD问题
max sub vector sum 问题
求教:贪心算法找零钱的精度问题?
相关话题的讨论汇总
话题: solution话题: prices话题: minvalue话题: maxdiff话题: int