循环遍历数组中的指定值

时间:2015-08-23 12:27:56

标签: java arrays loops

说我给了数组

declare @sql nvarchar(max) = '
select SalesOrderID 
from sales.SalesOrderDetail 
where 1=1 ';

if (@detailId is not null)
begin
    @sql := @sql + 'SalesOrderDetailID = ' + cast(@detailId as varchar(255));
end;

exec sp_execute_sql @sql;

然后,假设我将5个数字分配给5个位置

declare @sql nvarchar(max) = '
select SalesOrderID 
from sales.SalesOrderDetail 
where 1 = 1 ';

if (@detailId is not null)
begin
    @sql := @sql + 'and SalesOrderDetailID = @detailid';
end;

exec sp_execute_sql @sql, '@detailid int', @detailid = @detailid

有没有办法可以遍历我指定的数字而没有列出“4,12,17,42,49”的列表并获得“2,0,5,8,4”的输出?

3 个答案:

答案 0 :(得分:2)

您可以使用盒装类型Integer,它可以为null。

Integer[] array = new Integer[50];

... assignment ...

for (Integer i : array)
    if (i != null)
        System.out.println(i);

答案 1 :(得分:2)

Is there a way I can loop through just the numbers I assigned without having a list that says "4, 12, 17, 42, 49" and get the output of "2, 0, 5, 8, 4"?

没有。你无法用数组做到这一点。这将破坏数组的目的。你实际上期望它的行为像地图。

为此目的使用适当的地图。这是一个例子

HashMap<Integer, Integer> map = new HashMap<>();
map.put(4, 2);
map.put(12, 0);
for(Integer value : map.values()) {
    System.out.println(value);
}

答案 2 :(得分:0)

是和否。

不,因为你必须迭代整个数组,除非你以某种方式存储设置的值(你不想要的)。

是的,您可以通过设置一些默认值来实现只获得所需的输出。例如,使用Integer.MIN_VALUE初始化数组,并仅处理不等于该值的值。

相关问题