简体   繁体   English

ArrayList或哈希集

[英]ArrayList or Hashset

ArrayList queryParms = new ArrayList();
StringBuffer sql = new StringBuffer();
sql.append(
"SELECT A.FLDREC_NUM, " +
"@CHARDATE(A.FLDDATE), " +
"T.FLDDESCR, @DEC(A.FLDLEVEL,3) " +
" FROM @SCHEMAALCOHOL A LEFT OUTER JOIN @SCHEMADRUGCAUS T " +
" ON A.FLDREASON = T.FLDCODE " +
" WHERE A.FLDEMPLOYEE = ? " +
" ORDER BY A.FLDDATE DESC"
);
queryParms.add(new Long(empRec));
  1. Can i use HashSet instead of ArrayList above and does it make any sense in terms of performance?. 我可以使用HashSet代替上面的ArrayList,并且在性能方面是否有意义?

  2. What does the query do, do we need to append the query in StringBuffer. 查询的作用是什么,我们需要将查询追加到StringBuffer中。 Why can't i directly add to ArrayList? 为什么我不能直接添加到ArrayList?

In general, you would want to use an ArrayList for query parameters - because the order matters. 通常,您会希望使用ArrayList作为查询参数-因为顺序很重要。 When you've only got a single parameter (as you have here) it's not an issue - but I'd definitely use a list for consistency. 当您只有一个参数(如此处所示)时,这不是问题-但我绝对会使用一个列表来保持一致性。

As for using StringBuffer - you haven't shown what you're doing with sql here. 至于使用StringBuffer ,这里没有显示您正在使用sql做什么。 If you're not appending anything else, you could use a simple String ... but you wouldn't be adding it to the ArrayList , as it's the query itself, not a query parameter . 如果您不追加任何其他内容,则可以使用简单的String ...,但不会将其添加到ArrayList ,因为它是查询本身,而不是查询参数

Finally, I'd recommend using generics, eg 最后,我建议使用泛型,例如

ArrayList<Long> queryParameters = new ArrayList<Long>();

As for performance, consider: 至于性能,请考虑:

  1. Using StringBuilder(instead of StringBuffer) which is not synchronized and is not an issue, since you're creating a new StringBuilder() for each request. 使用StringBuilder(而不是StringBuffer)是不同步的,也不是问题,因为您正在为每个请求创建一个新的StringBuilder()。 If it's the same statement used for each request, it should be a final String, globally declared. 如果与每个请求使用的语句相同,则应为全局声明的最终String。

  2. As suggested by Jon, use ArrayList with Generics. 正如Jon所建议的,将ArrayList与Generics一起使用。 The queryParams is used as a part of QueryService implementation used to query DB. queryParams用作用于查询数据库的QueryService实现的一部分。 As it appears, it's a pre-compiled sql query and order of query params is important at run-time. 看起来,这是一个预编译的sql查询,查询参数的顺序在运行时很重要。 HashSet doesn't guarantee order. HashSet不保证顺序。

more efficient: 更高效:

sql.append("SELECT A.FLDREC_NUM, ");
sql.append("@CHARDATE(A.FLDDATE), ");
......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM